📅  最后修改于: 2020-09-25 06:02:24             🧑  作者: Mango
如果一个正整数称为阿姆斯特朗数(n阶),如果
abcd... = an + bn + cn + dn + ...
对于3位数的阿姆斯特朗数,每个数位的立方和等于该数字本身。例如,153是Armstrong的数字,因为
153 = 1*1*1 + 5*5*5 + 3*3*3
#include
using namespace std;
int main() {
int num, originalNum, remainder, result = 0;
cout << "Enter a three-digit integer: ";
cin >> 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)
cout << num << " is an Armstrong number.";
else
cout << num << " is not an Armstrong number.";
return 0;
}
输出
Enter a positive integer: 371
371 is an Armstrong number.
在程序中,我们迭代while循环,直到originalNum
为0。
在循环的每次迭代中,将orignalNum
的最后一位数字的多维数据集添加到result
。
remainder = originalNum % 10;
result += remainder * remainder * remainder;
并且,最后一位从orignalNum
删除。
循环结束时,单个数字的立方的总和存储在result
。
#include
#include
using namespace std;
int main() {
int num, originalNum, remainder, n = 0, result = 0, power;
cout << "Enter an integer: ";
cin >> num;
originalNum = num;
while (originalNum != 0) {
originalNum /= 10;
++n;
}
originalNum = num;
while (originalNum != 0) {
remainder = originalNum % 10;
// pow() returns a double value
// round() returns the equivalent int
power = round(pow(remainder, n));
result += power;
originalNum /= 10;
}
if (result == num)
cout << num << " is an Armstrong number.";
else
cout << num << " is not an Armstrong number.";
return 0;
}
输出
Enter an integer: 1634
1634 is an Armstrong number.
在此程序中,首先计算输入数字的位数,并将其存储在n
。
而且, pow()
函数在while
循环的每次迭代中计算单个数字的幂。