gowthz
gowthz

Reputation: 469

Program to Armstrong Number of 'n' digits is giving wrong output for only 153

My program to check Armstrong Number of 'n' digits is giving a wrong output, only when the input is 153.

Here is my code.

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

int main()
{
    int p, k, n, t, sum, n1, m;
    printf("Enter the number: ");
    scanf("%d", &n);
    n1=n;
    for(p=0, k=1; n/k>=1; ++p, k*=10);
    printf("\nThe number of digits: %d", p);

    for(sum=0; n>0; n/=10)
    {
        t= n%10;
        printf("\n\nThe base and power: %d and %d", t, p);
        m=pow(t, p);
        printf("\nThe calculated no is: %d", m);
        sum+=pow(t, p);
        printf("\nThe sum is: %d", sum);
    }

    printf("\n\t The original number is  : %d", n1);
    printf("\n\t The calculated number is: %d", sum);

    if(n1==sum)
        printf("\n\t%d is an armstrong number\n", n1);
    else
        printf("\n\t%d is not an armstrong number\n", n1);

    return 0;
}

The program is getting 152 when it does the math and is therefore giving a wrong output. I have printed every step to find the exact point of error.

The problem is, it is calculating the cube of 5 as 124.

Interestingly I am getting the correct answer(125) when I use the power function to calculate the cube of 5 in a separate, simple program.

I also checked the code given here -->https://www.programiz.com/c-programming/examples/check-armstrong-number which is also giving the wrong output. The answers to the somewhat similar questions that I found on this website didn't solve the problem.

Upvotes: 0

Views: 1383

Answers (2)

amit
amit

Reputation: 1

There are Two ways to solve. 1) Use round() function which will give the nearest integer (because there is some error in floating point calculation in codeblocks).

2) Declare your sum variable as float or double because then it will convert into perfect floating point precision.

Upvotes: 0

4386427
4386427

Reputation: 44329

Well, I'm not able to reproduce the said problem. I do get the correct result for input 153, i.e. that it is an Armstrong number.

It could be some floating point rounding error due to use of pow (though I would find that strange in this specific case).

For a task like this one, you should not use floating point. Use the largest integer type available. Not only do you avoid nasty rounding errors but you also increases the range of input values that your program can handle.

So, I like to address this part:

I cannot use t* t*t as this program is for Armstrong numbers of "n" digits, and not only 3

You can easily write a function that calculates t^n using integer math. Here is an example:

#include<inttypes.h>

uint64_t intpow(uint64_t t, uint64_t p)
{
    uint64_t result = 1;
    while(p>0)
    {
        result = result * t;
        --p;
    }
    return result;
} 

Notice: In its current form the function lacks overflow detection as I wanted to keep the function simple.

Upvotes: 3

Related Questions