C++ 显示两个区间内的阿姆斯特朗数程序

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


此程序要求用户输入两个整数,并显示给定区间内的所有阿姆斯特朗数。

如果您不知道如何检查数字是否为阿姆斯特朗数,那么这个程序可能看起来有点复杂。

请访问此页面了解 阿姆斯特朗数以及如何在 C++ 编程中检查它

示例:显示区间内的阿姆斯特朗数

#include <iostream>
#include <cmath>
using namespace std;

int main() {

  int num1, num2, i, num, digit, sum, count;

  cout << "Enter first number: ";
  cin >> num1;

  cout << "Enter second number: ";
  cin >> num2;

  // swap if num1 > num2
  if (num1 > num2) {
    num1 = num1 + num2;
    num2 = num1 - num2;
    num1 = num1 - num2;
  }
  
  cout << "Armstrong numbers between " << num1 << " and " << num2 << " are: " << endl;
 
  // print Armstrong numbers from num1 to num2
  for(i = num1; i <= num2; i++) {

    // count gives the number of digits in i
    count = 0;
         
    // store value of i in num
    num = i;

    // count the number of digits in num and i
    while(num > 0) {
      ++count;
      num /= 10;
    }
 
    // initialize sum to 0
    sum = 0;

    // store i in num again    
    num = i;
        
    // get sum of power of all digits of i
    while(num > 0) {
      digit = num % 10;
      sum = sum + pow(digit, count);
      num /= 10;
    }

    // if sum is equal to i, then it is Armstrong
    if(sum == i) {
      cout << i << ", ";
    }
  }

  return 0;
}

输出

Enter first number: 1
Enter second number: 10000
Armstrong numbers between 1 and 10000 are:
1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474,

此程序打印给定区间内的所有阿姆斯特朗数,其中区间的起点和终点都包含在内。

首先,我们获取用户输入的 num1num2 来确定我们的区间。如果 num1 的值大于 num2,我们 交换这两个数字

然后,我们使用 for 循环找到所有阿姆斯特朗数

for(i = num1; i <= num2; i++) {
  // code to print Armstrong numbers
}

第 1 步:查找 i 的数字位数

首先,我们需要计算区间内每个数字的位数。换句话说,我们需要计算 i 的数字位数。

因此,在循环中,i 的值存储在变量 num 中。然后,我们使用 while 循环 来计算 num 的数字位数。

count = 0;
num = i;

// count the number of digits in num and i
while(num > 0) {
  ++count;
  num /= 10;
}

while 循环结束后,count 变量将给出 i 的数字位数。


第 2 步:查找每个数字的幂之和

我们知道阿姆斯特朗数是指其每个数字的幂之和(幂的指数是数字的总位数)等于该数字本身。

因此,我们的下一步是找到这个和。与上一步类似,我们将 sum 变量初始化为 0,并将 i 的值赋给 num

sum = 0;
num = i;

然后,我们使用 while 循环来查找数字的幂之和,该数字的幂是 count 变量的值。

while(num > 0) {
  digit = num % 10;
  sum = sum + pow(digit, count);
  num /= 10;
}

请注意,我们使用了 pow() 函数来计算数字的幂(**digit ^ count**)。要使用此函数,我们必须将 cmath 头文件导入到我们的程序中。


第 3 步:检查 sum 是否等于 i

最后,将 sum 与原始数字 i 进行比较。如果它们相等,则该数字是阿姆斯特朗数,因此我们将其打印到屏幕上。

if(sum == i) {
  cout << i << ", ";
}
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战