原文: https://www.programiz.com/c-programming/examples/check-armstrong-number

在此示例中,您将学习检查用户输入的整数是否是阿姆斯特朗数。

要理解此示例,您应该了解以下 C 编程主题:


如果一个正整数称为阿姆斯特朗数(阶数n),则

  1. abcd... = a<sup>n</sup> + b<sup>n</sup> + c<sup>n</sup> + d<sup>n</sup> +

对于 3 位的阿姆斯特朗数,每个数字的立方数之和等于数字本身。 例如,153 是阿姆斯特朗数,因为

  1. 153 = 1*1*1 + 5*5*5 + 3*3*3

检查阿姆斯特朗三位数

  1. #include <stdio.h>
  2. int main() {
  3. int num, originalNum, remainder, result = 0;
  4. printf("Enter a three-digit integer: ");
  5. scanf("%d", &num);
  6. originalNum = num;
  7. while (originalNum != 0) {
  8. // remainder contains the last digit
  9. remainder = originalNum % 10;
  10. result += remainder * remainder * remainder;
  11. // removing last digit from the orignal number
  12. originalNum /= 10;
  13. }
  14. if (result == num)
  15. printf("%d is an Armstrong number.", num);
  16. else
  17. printf("%d is not an Armstrong number.", num);
  18. return 0;
  19. }

输出

  1. Enter a three-digit integer: 371
  2. 371 is an Armstrong number.

检查阿姆斯特朗 n 位数字

  1. #include <math.h>
  2. #include <stdio.h>
  3. int main() {
  4. int num, originalNum, remainder, n = 0;
  5. float result = 0.0;
  6. printf("Enter an integer: ");
  7. scanf("%d", &num);
  8. originalNum = num;
  9. // store the number of digits of num in n
  10. for (originalNum = num; originalNum != 0; ++n) {
  11. originalNum /= 10;
  12. }
  13. for (originalNum = num; originalNum != 0; originalNum /= 10) {
  14. remainder = originalNum % 10;
  15. // store the sum of the power of individual digits in result
  16. result += pow(remainder, n);
  17. }
  18. // if num is equal to result, the number is an Armstrong number
  19. if ((int)result == num)
  20. printf("%d is an Armstrong number.", num);
  21. else
  22. printf("%d is not an Armstrong number.", num);
  23. return 0;
  24. }

输出

  1. Enter an integer: 1634
  2. 1634 is an Armstrong number.

在该程序中,首先计算一个整数的位数,并将其存储在n中。 并且,pow()函数用于计算第二for循环的每次迭代中各个数字的幂。