In this article, we will write a C program to add two floating point numbers. The program takes two floating point numbers from the user as input, calculates their sum and prints the result on the output screen.
Sample Example:
Input:
Enter the first number: 12.5
Enter the second number: 13.35
Output:
The sum of two numbers is: 25.85
In C, a floating point number represents a real number that has a fractional part. In simple words, a floating point number is nothing but a number having a decimal point for eg. 10.5, 12.34, 100.0, etc.
Floating point numbers have a data type of float and they are represented by %f
format specifier.
To add two floating point numbers in C, we can use the addition operator(+
). It takes two operands and returns their sum as a result.
The sum of two floating point numbers is always a floating point number.
The following C program shows how you can add two floating point numbers:
// C Program to add two floating point numbers #include <stdio.h> int main() { float num1, num2, sum; printf("Enter the first number: "); scanf("%f", &num1); printf("Enter the second number: "); scanf("%f", &num2); // Calculate the sum of num1 and num2 sum = num1 + num2; // Print the result printf("The sum of two numbers is: %.2f", sum); return 0; }
Output:
Enter the first number: 12.5 Enter the second number: 13.35 The sum of two numbers is: 25.85
Explanation
In the above program, the user is first asked to enter two floating point numbers using the printf()
function.
The first number entered by the user is stored in the variable num1
and the second number is stored in the num2
variable.
Note that we have used the %f
format specifier inside the scanf()
function to take the floating point number from the user.
After taking the floating point numbers from the user as input, we have calculated their sum using the below statement:
sum = num1 + num2;
The sum of the two numbers is stored in the sum
variable.
Finally, we print the sum of the two floating point numbers using the printf()
function. But wait, if you pay enough attention in the last printf()
, you will find that we have used %.2f
format specifier instead of %f
to print the sum.
Why this is so?
Actually, when we use %.2f
, we are telling printf
to format the floating-point number with a precision of two digits after the decimal point. By default, floating point numbers are printed up to 6 digits after the decimal point.
Therefore output is 25.85 instead of 25.850000 when we use %.2f
instead of %f
.
I hope you will find this article helpful. Thanks for reading.