|
math not quite accurate in C program
I am a newb, just started learning C a few days ago. I wrote a program that calculates factorials and displays them in scientific notation.
Example:
$ ./factorial
3
3 factorial is 6.00000000000000000000000000000000000000000000000e 0
It works fine. But when I try to do a number that requires the scientific notation to be used, it is slightly off.
Example:
$ ./factorial
4
4 factorial is 2.39999999999999991118215802998747676610946655273e 1
Here is the code:
main()
{
int num,e,x;
double work=1.0;
scanf("%d", &num);
for (x=1; x<=num; ++x)
{
work=work*x;
while (work>=10.0)
{
work=work/10.0;
++e;
}
}
printf ("%d factorial is %47.47fe%d\n",num,work,e);
}
Please help me to diagnose what is wrong with my program!
|