📜  C++程序检查Armstrong号码(1)

📅  最后修改于: 2023-12-03 14:59:52.266000             🧑  作者: Mango

C++程序检查Armstrong号码

Armstrong号码是指一个n位数(n>=3),它每个数位的n次幂之和等于它本身。例如,153是一个3位的Armstrong号码,因为1³ + 5³ + 3³ = 153。

以下是C++程序来检查Armstrong号码:

#include <iostream>
#include <cmath>

using namespace std;

int main() {
    int num, temp, digits = 0, sum = 0;

    // 获取输入
    cout << "Enter a positive integer: ";
    cin >> num;

    // 计算位数
    temp = num;
    while (temp != 0) {
        digits++;
        temp /= 10;
    }

    // 计算Armstrong号码
    temp = num;
    while (temp != 0) {
        int digit = temp % 10;
        sum += pow(digit, digits);
        temp /= 10;
    }

    // 检查Armstrong号码
    if (sum == num)
        cout << num << " is an Armstrong number." << endl;
    else
        cout << num << " is not an Armstrong number." << endl;

    return 0;
}

此程序从用户输入中获取一个正整数,计算其位数并检查是否为Armstrong号码。它首先使用一个while循环来计算数字的位数,然后使用另一个while循环计算Armstrong号码的值。最后,它将计算的值与原始输入进行比较,以确定是否为Armstrong号码,并输出相应的消息。

结论

通过此C++程序,您可以轻松检查一个数字是否为Armstrong号码。如果您想了解更多关于C++编程的信息,请参阅C++编程教程。