🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# C 程序:检查阿姆斯特朗数 > 原文: [https://www.programiz.com/c-programming/examples/check-armstrong-number](https://www.programiz.com/c-programming/examples/check-armstrong-number) #### 在此示例中,您将学习检查用户输入的整数是否是阿姆斯特朗数。 要理解此示例,您应该了解以下 [C 编程](/c-programming "C tutorial")主题: * [C `if...else`语句](/c-programming/c-if-else-statement) * [C `while`和`do...while`循环](/c-programming/c-do-while-loops) * * * 如果一个正整数称为阿姆斯特朗数(阶数`n`),则 ```c abcd... = a<sup>n</sup> + b<sup>n</sup> + c<sup>n</sup> + d<sup>n</sup> + ``` 对于 3 位的阿姆斯特朗数,每个数字的立方数之和等于数字本身。 例如,153 是阿姆斯特朗数,因为 ```c 153 = 1*1*1 + 5*5*5 + 3*3*3 ``` * * * ## 检查阿姆斯特朗三位数 ```c #include <stdio.h> int main() { int num, originalNum, remainder, result = 0; printf("Enter a three-digit integer: "); scanf("%d", &num); originalNum = num; while (originalNum != 0) { // remainder contains the last digit remainder = originalNum % 10; result += remainder * remainder * remainder; // removing last digit from the orignal number originalNum /= 10; } if (result == num) printf("%d is an Armstrong number.", num); else printf("%d is not an Armstrong number.", num); return 0; } ``` **输出** ```c Enter a three-digit integer: 371 371 is an Armstrong number. ``` * * * ## 检查阿姆斯特朗 n 位数字 ```c #include <math.h> #include <stdio.h> int main() { int num, originalNum, remainder, n = 0; float result = 0.0; printf("Enter an integer: "); scanf("%d", &num); originalNum = num; // store the number of digits of num in n for (originalNum = num; originalNum != 0; ++n) { originalNum /= 10; } for (originalNum = num; originalNum != 0; originalNum /= 10) { remainder = originalNum % 10; // store the sum of the power of individual digits in result result += pow(remainder, n); } // if num is equal to result, the number is an Armstrong number if ((int)result == num) printf("%d is an Armstrong number.", num); else printf("%d is not an Armstrong number.", num); return 0; } ``` **输出** ```c Enter an integer: 1634 1634 is an Armstrong number. ``` 在该程序中,首先计算一个整数的位数,并将其存储在`n`中。 并且,`pow()`函数用于计算第二`for`循环的每次迭代中各个数字的幂。