I use Code::Block 10.02 and When print Amstrong Number in C.I wait a result like this:
153
370
371
407
But It's only print:
153
370
371
This is my code in C:
#include <stdio.h>
#include <conio.h>
#include <math.h>
int main()
{
int a,b,c;
for (a=1;a<=9;a++)
for(b=0;b<=9;b++)
for(c=0;c<=9;c++)
{
if(pow(a,3)+pow(b,3)+pow(c,3)==100*a+10*b+c)
printf("\n%d%d%d",a,b,c);
}
}
And this is my screen: http://daynhauhoc.com/uploads/default/3011/9598a2ad2183198f.png
But, when i use this code, It's Work very well:
#include <stdio.h>
#include <conio.h>
#include <math.h>
int main()
{
int a,b,c;
for (a=1;a<=9;a++)
for(b=0;b<=9;b++)
for(c=0;c<=9;c++)
{
int d=pow(a,3)+pow(b,3)+pow(c,3);
int e=100*a+10*b+c;
if(d==e)
printf("\n%d%d%d",a,b,c);
}
}
Someone tell me a explantion please?
Oh i know why!! You use pow(a,3)+pow(b,3)+pow(c,3)==100*a+10*b+c
However pow()
return double
you use ==
to determine whether the same float and integer.
Don't use ==
or !=
between integer and float!
The problem is most likely that the pow ()
function is a floating-point function with rounding errors. So pow (4, 3)
is not 64, but some number very very close to 64. You will be comparing 407 and a number that is very, very close to 407 and that will sometimes fail.
Instead of pow (a, 3)
, just write a*a*a
.
BTW. The rounding errors depend on the exact implementation of pow
, which isn't exactly the same on every computer. So this number that is "very very close to 407" may be "just very slightly larger" on one computer, "just very slightly smaller" on another, and by coincidence it may be "exactly 407" on a third computer. Which explains why someone says "works for me" and someone else says "doesn't work".
BTW. By converting to int, your result is rounded down to an integer. So if one computer gets 407.000000000000000001, that is rounded down to 407, but if another computer gets 406.999999999999999999, that is rounded down to 406.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With