I am writing a very basic program in C to check whether a number is an Armstrong number or not and I am having some trouble in understanding why one version works and the other doesn't.
My code is:
#include<stdio.h>
int main()
{
int n,num,rem,sum=0;
printf("enter n:
");
scanf("%d",&n);
for(num=n;num!=0;num/=10){
rem=num%10;
sum+=rem*rem*rem;
}
if(sum==n){
printf("armstrong number");
}
else{
printf("not");
}
return 0;
}
enter n:
153
armstrong number
--------------------------------
Process exited after 2.716 seconds with return value 0
Press any key to continue . . .
Now, this runs smoothly, no problem. But when I write
if(sum==num)
the code shows that 153 (which is an Armstrong number) is not an Armstrong number!
I have already written num=n;
then why does changing num
and n
in the if
statement show different results?
This is the result when I put num
in if
statement.
enter n:
153
not an armstrong number
--------------------------------
Process exited after 1.702 seconds with return value 0
Press any key to continue . . .
question from:
https://stackoverflow.com/questions/66065065/why-do-i-get-different-results-with-two-ways-of-checking-whether-a-number-is-an 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…