Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

c - Why do I get different results with two ways of checking whether a number is an Armstrong number or not?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

num is modified during the for loop while n isn't.

num will be zero after the for loop because the loop condition is num!=0.

Therefore, num after the for loop doesn't have information to judge if n is an armstrong number.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...