Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ ตรวจสอบเลขอาร์มสตรอง (Armstrong Number)


Armstrong Number: ผลรวมตัวเลขแต่ละหลักยกกำลังจำนวนหลัก = เลขเดิม

3 = 3^1
153 = 1^3 + 5^3 + 3^3 = 153
371 = 3^3 + 7^3 + 1^3 = 371
407 = 4^3 + 0^3 + 7^3 = 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

อธิบายขั้นตอน (เหมือนบทความก่อนหน้า แต่เช็คตัวเลขเดียว)

  1. นับจำนวนหลัก digitNum
  2. คำนวณ digitSum = Σ (digit^digitNum)
  3. เปรียบเทียบ num กับ digitSum
// นับหลัก
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";