C Program to find the sum of integer and fractional part separately

In this section, you will learn how to write a C Program to find the sum of integer and fractional part separately.

For eg.

Input – Suppose you have two float type variables a and b and the values are 

                a = 12.37  and   b= 6.15

Output – 18.52  ( 12+6=18 and .37+.15=.52 )

When you typecast the float variable into an int variable. It gets rounded down and stored as an integer value.
Now we can subtract the integer part from the float part and can get our desired fractional part with ease.

C Program to find the sum of integer and fractional part separately

/* C-Program: Read two real (float) values and find the sum of integer and fractional part separately */ 

#include <stdio.h> 

int main() 
{ 

float x,y; 

printf("Enter the values of x and y:\n"); 
scanf("%f%f", &x,&y); 

printf("\nsum of integer part = %d \n", (int)x + (int)y); 
printf("\nsum of fractional part = %f \n", x-(int)x + y-(int)y); 

return 0;

}

Output :-

Enter the values of x and y:
52.31 22.90

sum of integer part = 74

sum of fractional part = 1.210001

Or A relatively foolproof way would be to convert the number to a string utilising general representation (no scientific or engineering notation), then splitting the result string into 2 parts at the decimal point (whatever that is in your locale), retaining the decimal point in the second part, and then parsing the 2 parts back into numbers to represent the integer and the fractional parts.

Related Articles

Leave a Reply