Home > Mobile >  Armstrong number in c programming
Armstrong number in c programming

Time:03-19

I made a program in c to find whether an integer is an armstrong number or not for three digits numbers. If the number that has been given by the user is an armstrong number it will print it is an armstrong number and if it is not an armstrong number it will print its not an armstrong number. It is not showing any errors. Also it works with all three digit numbers except for a number. It is 153. It is printing that it is not an armstrong number eventhough it is an armstrong number. Could anyone tell me whats wrong here. here is the code and output:

#include <math.h>
#include <stdio.h>
int main(){

    int sum = 0;
    int n;

    //asking the user to enter a number
    printf("Enter a number : ");
    scanf("%d",&n);

    // copying the value of n in a variable b
    int b = n;


    while(n!=0){
        // storing the reminders of n divided by 10 in a variable
        int r = n;
    
        // finding the power 
        sum = pow(r,3) sum;
        n = n/10;
    }
    // here i am printing the sum just to show you guys what is the answer i am getting
       printf("%d\n",sum);

       // if sum equals to b, then do this
       if (sum==b){
           printf("The number is an armstrong number\n");
    }
        // if not then do this
       else{
           printf("It is not an armstrong number\n");
    }
}

Here is the output i am getting if i enter a three digit armstrong number:

Enter a number : 370
370
The number is an armstrong number

Enter a number : 407
407
The number is an armstrong number

Here i am entering a number which is not an armstrong number:

Enter a number : 100
1
It is not an armstrong number

153 is an armstrong number. Here is what happens when i enter 153:

Enter a number : 153
152
It is not an armstrong number

It is saying 153 is not a armstrong number. Why does this happen? How to solve this? please reply

CodePudding user response:

The pow implementation in your standard C library is deficient and returns an approximation even when the mathematical result is exactly representable.

Stop using it for cubes. Replace pow(r,3) with r*r*r.

CodePudding user response:

Your code is working on gcc compilers. check for yourself https://godbolt.org/z/Pvo19xrxx

as mentioned by others use r*r*r instead of pow.

  •  Tags:  
  • c
  • Related