I am given two values, the integer and the fractional parts of a double. What is the best way to form the double value? Essentially, it would be the opposite of modf()
.
I'm doing this in swift, but any mathematical way is what I'm looking for.
let integer = 12
let fractional = 34
let d = ???(12, 34) // 12.34
For general case you have to find the number of digits are there in the fraction part. So I am assuming that x as integer part and y as fractional part. Then you have to divide y by 10 to the power of number of digits in y. And then you have to add x to the updated y value.
Here is the code,
#include <stdio.h>
#include<math.h>
int main()
{
int x,y;
scanf("%d %d",&x,&y);
int count = 0;
int z = y;
while(z>0)
{
count+=1;
z = z/10;
}
float ans = 0;
ans = (double)x + (double)y/pow(10,count);
printf("%f",ans);
return 0;
}
Hope this solves your problem.
If x and y are also considered as float there is even a better solution. Thanks to Joël Hecht
#include <stdio.h>
#include<math.h>
int main()
{
double x,y;
scanf("%lf %lf",&x,&y);
while(y>=1)
{
y = y/10.0;
}
printf("%lf",x+y);
return 0;
}
P.S :- You have to take care if the number given is negative.