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

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


เลขอาร์มสตรอง คือเลขที่ผลรวมของกำลังสามของตัวเลขแต่ละหลัก เท่ากับตัวเลขนั้นเอง แนวคิดคณิตศาสตร์พื้นฐานสำหรับฝึกตรรกะการเขียนโปรแกรม

Input: 370 Output: 370 is an Armstrong Number

คำอธิบาย

370 = 3*3*3 + 7*7*7 + 0*0*0 = 27 + 343 + 0 = 370

ตัวอย่าง

#include <iostream>
using namespace std;
int main() {
    int n, num, rem, sum = 0;
    cin >> n;
    num = n;
    while (num != 0) {
        int digit = num % 10;
        sum += digit * digit * digit;
        num /= 10;
    }
    if (sum == n)
        printf("%d is an Armstrong number.", n);
    else
        printf("%d is not an Armstrong number.", n);
    return 0;
}