在 C 中使用幂函数

问题描述 投票:0回答:1

我正在编写一个程序,我必须检查用户输入的数字是否为 armstrong 以进行计算我正在使用幂函数,但似乎有错误。我试图检查我的代码中的错误,所以我为 while 循环的每次迭代打印出 rem,事实证明,当我将 153 作为输入(这是一个 armstrong 数字)时,第二次迭代的 rem 值是结果是 124,但应该是 125(pow(5,3))。

这是我的代码:

// 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;
}
c pow
1个回答
-2
投票

我复制了你的代码并在我的 64 位 Windows 机器上运行它(通常用 gcc 编译)。我得到了正确的结果:

Enter the number you want to check :
153
the rem is 27
the total is 27
the rem is 125
the total is 152
the rem is 1
the total is 153
The number entered is an armstrong number

你运行代码的环境是什么?

© www.soinside.com 2019 - 2024. All rights reserved.