Menu Close

C语言练习:检查并打印出输入的两个输入的整数之间的阿姆斯壮(Armstrong)数

阿姆斯壮数(armstrong number) 定义:阿姆斯壮数(armstrongnumber) 是等于其数字的立方数之和的数字,例如:0,1,153,370,371,407等。
现在试着理解为什么153是一个阿姆斯壮数字, 153 = (1*1*1)+(5*5*5)+(3*3*3)。

153 = (1*1*1)+(5*5*5)+(3*3*3)
(1*1*1)=1
(5*5*5)=125
(3*3*3)=27
So:
1+125+27=153

C语言检查输入数据是不是阿姆斯壮数

#include <math.h>
#include <stdio.h>
int main() {
  int low, high, number, originalNumber, rem, count = 0;
  double result = 0.0;
  printf("Enter two numbers(intervals): ");
  scanf("%d %d", &low, &high);
  printf("Armstrong numbers between %d and %d are: ", low, high);

  // swap numbers if high < low
  if (high < low) {
    high += low;
    low = high - low;
    high -= low;
  }
   
  // iterate number from (low + 1) to (high - 1)
  // In each iteration, check if number is Armstrong
  for (number = low + 1; number < high; ++number) {
    originalNumber = number;

    // number of digits calculation
    while (originalNumber != 0) {
      originalNumber /= 10;
      ++count;
    }

    originalNumber = number;

    // result contains sum of nth power of individual digits
    while (originalNumber != 0) {
      rem = originalNumber % 10;
      result += pow(rem, count);
      originalNumber /= 10;
    }

    // check if number is equal to the sum of nth power of individual digits
    if ((int)result == number) {
      printf("%d ", number);
    }

    // resetting the values
    count = 0;
    result = 0;
  }

  return 0;
}
Enter two numbers(intervals): 200
2000
Armstrong numbers between 200 and 2000 are: 370 371 407 1634
READ  C语言练习:给出一个整数,计算出该整数有几个数字(digits)构成
除教程外,本网站大部分文章来自互联网,如果有内容冒犯到你,请联系我们删除!

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Leave the field below empty!

Posted in C 决策和循环语句

Related Posts