浮動小数点数の算術演算を行う
このステップでは、C 言語で浮動小数点数に対して加算、減算、乗算、除算などの様々な算術演算を行う方法を学びます。
浮動小数点数の算術演算をデモンストレーションするために、前のファイルを修正しましょう。
cd ~/project
nano floating_arithmetic.c
以下のコードをファイルに追加します。
#include <stdio.h>
int main() {
// Declare floating-point variables
float a = 10.5;
float b = 3.2;
// Addition
float sum = a + b;
printf("Addition: %.2f + %.2f = %.2f\n", a, b, sum);
// Subtraction
float difference = a - b;
printf("Subtraction: %.2f - %.2f = %.2f\n", a, b, difference);
// Multiplication
float product = a * b;
printf("Multiplication: %.2f * %.2f = %.2f\n", a, b, product);
// Division
float quotient = a / b;
printf("Division: %.2f / %.2f = %.2f\n", a, b, quotient);
// Mixed arithmetic operations
float mixed_calc = (a + b) * (a - b) / b;
printf("Mixed Calculation: (%.2f + %.2f) * (%.2f - %.2f) / %.2f = %.2f\n",
a, b, a, b, b, mixed_calc);
return 0;
}
プログラムをコンパイルして実行します。
gcc floating_arithmetic.c -o floating_arithmetic
./floating_arithmetic
出力例:
Addition: 10.50 + 3.20 = 13.70
Subtraction: 10.50 - 3.20 = 7.30
Multiplication: 10.50 * 3.20 = 33.60
Division: 10.50 / 3.20 = 3.28
Mixed Calculation: (10.50 + 3.20) * (10.50 - 3.20) / 3.20 = 24.41
浮動小数点数の算術演算に関する要点:
- 小数点以下の精度を制御するには
%.2f
書式指定子を使用します。
- 浮動小数点数の演算は標準的な数学の規則に従います。
- 浮動小数点数の計算では、潜在的な精度の制限に注意してください。