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

int main()
{
    int n, num, sum=0, count=0, a, remain=0;
    printf("Enter a number : ");
    scanf("%d", &num);
    a=num;
    n=num;

    while(a!=0)
    {
        a=a/10;
        count++;
    }

    while(n!=0)
    {
        remain=n%10;
        sum=sum+pow(remain, count);
        printf("%d\n", sum);
        n=n/10;
    }

    if(sum==num)
        printf("Armstrong Number");
    else
        printf("Not an Armstrong Number");

    return 0;
}

guys I am trying to make a program of checking if a number is Armstrong number or not. And I am facing this problem with '153' as an input specifically. The program works fine with various inputs but compiler is showing unusual behavior while adding 153. I will also attach the output with different inputs explicitly showing the addition of numbers in the 'sum' variable.

OUTPUT:

Enter a number : 153
27
151
152
Not an Armstrong Number

Enter a number : 371
1
344
371
Armstrong Number
  • `pow` is a floating point function, so it's not guaranteed give exact integer results. See [Is floating point math broken](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) for more about that. You need to write the code without using an floating point numbers or functions. – user3386109 Sep 18 '20 at 18:33
  • will using a typecast help? – Mohsin Khan Sep 18 '20 at 18:34
  • Nope, in your case `pow(5,3)` is returning something like `124.99999`. The implicit conversion to `int` and a type cast to `int` will both give you 124. – user3386109 Sep 18 '20 at 18:36
  • @user3386109 thanks for the help! – Mohsin Khan Sep 18 '20 at 18:40

1 Answers1

1

pow returns a double, which means you could have weird rounding issues. You may want to consider implementing your own integer exponentiation function.

Aplet123
  • 33,825
  • 1
  • 29
  • 55