Responsive Ads Here

Friday, August 5, 2016

How to Assign Fractional Numbers in C

A different variable is needed to assign fractional numbers. Before understand, let’s write a problem.


Code :

#include <stdio.h>  
 int main()  
 {  
     int a = 50, b = 60, sum;  
     sum = a + b;  
     printf("%d + %d = %d", a, b, sum);  
     return 0;  
 }
Output :



Run the program. See the result is 50+60=110. That means the output is right. But If we write the following problem,


Code :

#include <stdio.h>  
 int main()  

 {  
     int a = 50.45, b = 60, sum;  
     sum = a + b;  
     printf("%d + %d = %d", a, b, sum);  
     return 0;  
 }  
Output:


See here we assign 50.45 in as a integer type variable a. Run the program and see the output. Compare the result with the previous. The result is same 110 alhtough we assign 50.45 in the 2nd program. That means the last resut is wrong. But where is the error? The error created when we assign 50.45 in a integer type variable cause a different variable named “double” is used to assign fractional numbers. So the codes should be,

Code :

#include <stdio.h>  
 int main()  

 {  
     double a = 50.45, b = 60, sum;  
     sum = a + b;  
     printf("%.2lf + %.2lf = %.2lf", a, b, sum);  
     return 0;  
}
Output:


%lf ( Small letter of L ) is used to print fractional numbers. How much numbers we want to print, we’ve to instruct this by writing the number after giving a point. So we wrote %.2lf.

Read the next article to know more,


No comments:

Post a Comment