In this step, you'll learn how to perform various arithmetic operations on floating-point numbers in C, including addition, subtraction, multiplication, and division.
Let's modify the previous file to demonstrate floating-point arithmetic:
cd ~/project
nano floating_arithmetic.c
Add the following code to the file:
#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;
}
Compile and run the program:
gcc floating_arithmetic.c -o floating_arithmetic
./floating_arithmetic
Example output:
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
Key points about floating-point arithmetic:
- Use
%.2f
format specifier to control decimal precision
- Floating-point operations follow standard mathematical rules
- Be aware of potential precision limitations with floating-point calculations