balaji gv
balaji gv

Reputation: 41

My program to verify Armstrong numbers fails for number 153

I did a program to verify the Armstrong number. The program successfully verifies the Armstrong numbers except 153. Can anyone help me out?

#include <stdio.h>
#include <math.h>
#include <conio.h>

void main()
{
    int n,m,i,r,s=0,temp,c,count=0;
    printf("Enter num: ");
    scanf("%d",&n);
    temp = n;
    m = n;
    while(m>0)
    {
        r = m%10;
        count++;
        m/=10;
    }

    while(n>0)
    {
        r = n%10;
        s = s + pow(r,count);
        n = n/10;
    }

    if(s == temp)
    {
        printf("%d is a Armstrong num",temp);
    }
    else
    {
        printf("%d is not a Armstrong num",temp);
    }
}

Upvotes: 1

Views: 156

Answers (1)

0___________
0___________

Reputation: 67709

Using pow (and more generally float numbers) in integer calculations is ALWAYS a very bad idea.

Your code with one small change:

int intpow(int r, int c)
{
    int result = 1;
    while(c--)
    {
        result *= r;
    }
    return result;
}

and instead of

s = s + pow(r,count);

lets use our new function:

s = s + intpow(r,count);

https://godbolt.org/z/dreeKvre9

Result (ta-dam!! - magic):

153 is a Armstrong  num

Upvotes: 3

Related Questions