C++程序显示两个区间之间的阿姆斯特朗数
阿姆斯特朗数是指其各位数字的立方和等于该数本身的数。
以下是一些阿姆斯特朗数的示例:
3 = 3^1 153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153 407 = 4^3 + 0^3 + 7^3 = 64 +0 + 343 = 407 1634 = 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634
显示两个区间之间的阿姆斯特朗数的程序如下所示。
示例
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int lowerbound, upperbound, digitSum, temp, remainderNum, digitNum ;
lowerbound = 100;
upperbound = 500;
cout<<"Armstrong Numbers between "<<lowerbound<<" and "<<upperbound<<" are: ";
for(int num = lowerbound; num <= upperbound; num++) {
temp = num;
digitNum = 0;
while (temp != 0) {
digitNum++;
temp = temp/10;
}
temp = num;
digitSum = 0;
while (temp != 0) {
remainderNum = temp%10;
digitSum = digitSum + pow(remainderNum, digitNum);
temp = temp/10;
}
if (num == digitSum)
cout<<num<<" ";
}
return 0;
}输出
Armstrong Numbers between 100 and 500 are: 153 370 371 407
在上面的程序中,找到了给定区间内的阿姆斯特朗数。这是通过多个步骤完成的。给出了区间的下限和上限。使用这些,从下限到上限启动一个for循环,并评估每个数字以查看它是否为阿姆斯特朗数。
这可以在以下代码片段中看到。
lowerbound = 100; upperbound = 500; cout<<"Armstrong Numbers between "<<lowerbound<<" and "<<upperbound<<" are: "; for(int num = lowerbound; num <= upperbound; num++)
在for循环中,首先找到数字(即num)中的位数。这可以通过为每个数字将digitNum加1来完成。
以下代码片段演示了这一点。
temp = num;
digitNum = 0;
while (temp != 0) {
digitNum++;
temp = temp/10;
}知道位数后,通过将每个数字的digitNum次幂(即位数)相加来计算digitSum。
这可以在以下代码片段中看到。
temp = num;
digitSum = 0;
while (temp != 0) {
remainderNum = temp%10;
digitSum = digitSum + pow(remainderNum, digitNum);
temp = temp/10;
}如果数字等于digitSum,则该数字为阿姆斯特朗数并将其打印出来。如果不是,则它不是阿姆斯特朗数。这在下面的代码片段中可以看到。
if (num == digitSum) cout<<num<<" ";
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP