I am writing a program in which I have to check whether the number entered by the user is armstrong or not to do the calculation I am using the power function but there seems to be an error. I tried to check for the erorr in my code so i printed out rem for each iteration of the while loop, it turns out that when i give 153 as input (which is an armstrong number), the value of rem for the second iteration is coming out to be 124 but it should be 125(pow(5,3)).
This is my code :
// program to check if the number entered by the user is armstrong or not
#include <stdio.h>
#include <math.h>
int main(int argc, char const *argv[])
{
int num, original_number, remainder, total = 0, num1, number_of_digits = 0, rem;
printf("Enter the number you want to check :\n");
scanf("%d", &num);
original_number = num;
num1 = num;
while (num > 0)
{
num = num / 10;
number_of_digits++;
}
while (num1 > 0)
{
remainder = num1 % 10;
rem = pow(remainder, number_of_digits);
printf("the rem is %d\n", rem);
total = total + rem;
printf("the total is %d\n", total);
num1 = num1 / 10;
}
if (total == original_number)
{
printf("The number entered is an armstrong number");
}
else
{
printf("The number entered is not an armstrong number");
}
return 0;
}
In reviewing your code and the comments above, often times it comes down to the context of the problem being solved. In this case, since the program is working with integer values, and the "pow" function is meant for floating point functionality as noted in the good comments above, it would be wise to devise an alternative to using that function which only involves integers.
In this case with the context of what the program is trying to accomplish, one could write a small integer type power function, or even simpler, just utilize a simple loop to derive the power of an integer digit. Following is a quick refactored bit of code that replaces the "pow" function with a "for" loop.
Testing this out with your value of "153" and with a four-digit test number results in the following terminal output.
Keep in mind, this is just one of an assortment of methods that can be used to provide the desired solution. But give that a try and see if it meets the spirit of your project.