Print and Verify the Results
In this final step, you'll learn how to format and verify the results of mixed-type arithmetic operations in C, focusing on precise output and result validation.
Open the previous file to continue our example:
cd ~/project
nano mixed_arithmetic.c
Update the main()
function with more detailed output and result verification:
#include <stdio.h>
#include <math.h>
int main() {
// Integer variables
int whole_number1 = 10;
int whole_number2 = 5;
// Floating-point variables
float decimal_number1 = 7.5;
float decimal_number2 = 3.2;
// Mixed-type arithmetic operations
float mixed_addition = whole_number1 + decimal_number1;
float mixed_multiplication = whole_number2 * decimal_number2;
float mixed_division = decimal_number1 / whole_number2;
// Detailed result printing with formatting
printf("Arithmetic Operation Results:\n");
printf("1. Mixed Addition: %d + %.1f = %.2f\n", whole_number1, decimal_number1, mixed_addition);
printf("2. Mixed Multiplication: %d * %.1f = %.2f\n", whole_number2, decimal_number2, mixed_multiplication);
printf("3. Mixed Division: %.1f / %d = %.2f\n", decimal_number1, whole_number2, mixed_division);
// Result verification
printf("\nResult Verification:\n");
printf("Mixed Addition Verification: %.2f == %.2f\n",
mixed_addition, (float)whole_number1 + decimal_number1);
printf("Mixed Multiplication Verification: %.2f == %.2f\n",
mixed_multiplication, (float)whole_number2 * decimal_number2);
printf("Mixed Division Verification: %.2f == %.2f\n",
mixed_division, decimal_number1 / whole_number2);
return 0;
}
Compile and run the program:
gcc mixed_arithmetic.c -o mixed_arithmetic
./mixed_arithmetic
Example output:
Arithmetic Operation Results:
1. Mixed Addition: 10 + 7.5 = 17.50
2. Mixed Multiplication: 5 * 3.2 = 16.00
3. Mixed Division: 7.5 / 5 = 1.50
Result Verification:
Mixed Addition Verification: 17.50 == 17.50
Mixed Multiplication Verification: 16.00 == 16.00
Mixed Division Verification: 1.50 == 1.50
Key points in this example:
- Using different format specifiers for precise output
- Demonstrating mixed-type arithmetic with addition, multiplication, and division
- Performing inline result verification
- Showing type conversion in arithmetic operations