main()
{
int fact,i=5,div=8;
float dec=0.427,temp,sum=0;

while(i)
{
temp=dec*10;  printf("%f\t",temp);
fact=(int)temp;
sum=sum+(fact/(float)div);	printf("%f\n",sum);
dec=temp-fact;
div=div*8;
i--;
}

printf("\n The Decimal part= %f",sum);
getch();
}
Output
4.270000         0.500000
2.700000         0.531250
6.999998         0.542969
9.999981         0.545166
9.999809         0.545441

The Decimal part= 0.545441

What results were you expecting?

Are you serious "Narue"?

Yes, of course. You posted code and no real question. Were you expecting us to be psychic?

I was expecting the third line in o/p as 7.000000 not 6.999998

That's a typical precision error in floating-point. If you want to round, it's easily done with a …

#include<stdio.h>
#include<math.h>
double round(double x)
{
return x > 0 ? floor(x + 0.5) : ceil(x - 0.5);
}

int main()
{
int fact,i=5;
float dec=0.427,temp,sum=0,div=8;
while(i)
{
temp=dec*10;
printf("%f\t",round(temp));
fact=(int)temp;
sum=sum+(fact/div);
printf("%f\n",sum);
dec=temp-fact;
div=div*8;
i--;
}
printf("\n The Decimal part= %f",sum);
return 0;
}

## All 12 Replies

What results were you expecting?

Are you serious "Narue"?

What results were you expecting?

I was expecting the third line in o/p as 7.000000 not 6.999998

Are you serious "Narue"?

Yes, of course. You posted code and no real question. Were you expecting us to be psychic?

I was expecting the third line in o/p as 7.000000 not 6.999998

That's a typical precision error in floating-point. If you want to round, it's easily done with a utility function:

double round(double x)
{
return x > 0 ? floor(x + 0.5) : ceil(x - 0.5);
}

Alternatively, you can add a precision to your format specifier and printf will round it properly for display. For example, "%.4f" will round to four places. But due to increasing imprecision, you still might not get the results you're expecting.

Narue u r kind enough to reply me!
But I really don't know how to put ur code to make my program work.
Can I ask u to help me with full working codes?
Please I've just started learning C.:-/

#include<stdio.h>
#include<math.h>
double round(double x)
{
return x > 0 ? floor(x + 0.5) : ceil(x - 0.5);
}

int main()
{
int fact,i=5;
float dec=0.427,temp,sum=0,div=8;
while(i)
{
temp=dec*10;
printf("%f\t",round(temp));
fact=(int)temp;
sum=sum+(fact/div);
printf("%f\n",sum);
dec=temp-fact;
div=div*8;
i--;
}
printf("\n The Decimal part= %f",sum);
return 0;
}

The sum result should be 0.544921875.
there is no change in the result even after the insertion of the code..

Then convert all values into individual digits in an integer array. Then you can ignore the fact that floating point values are not exact.

Then convert all values into individual digits in an integer array. Then you can ignore the fact that floating point values are not exact.

Please modify my C source code.