C++ 程序检查阿姆斯特朗数
阿姆斯特朗数是一个数,其各个数位之和的数字方幂等于该数本身。一些阿姆斯特朗数的示例如下。
3 = 3^1 153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153 371 = 3^3 + 7^3 + 1^3 = 27 + 343 + 1 = 371 407 = 4^3 + 0^3 + 7^3 = 64 +0 + 343 = 407
一个检查一个数是否为阿姆斯特朗数的程序如下。
示例
#include <iostream>
#include <cmath<
using namespace std;
int main() {
int num = 153, digitSum, temp, remainderNum, digitNum ;
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<<" is an Armstrong number";
else
cout<<num<<" is not an Armstrong number";
return 0;
}输出
153 is an Armstrong number
在上述程序中,它确定给定的数字是否是阿姆斯特朗数。这是通过多步骤完成的。第一步是找到数字中的位数。这是通过为每个位数添加一个 digitNum 来完成的。
以下代码段对此进行了演示 −
temp = num;
digitNum = 0;
while (temp != 0) {
digitNum++;
temp = temp/10;
}在知道位数之后,通过将每个位数的数字方幂相加(即位数)来计算 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<<" is an Armstrong number"; else cout<<num<<" is not an Armstrong number";
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP