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

ตรวจสอบเลขอาร์มสตรอง (Armstrong Number) ด้วย C

โจทย์

ตรวจสอบว่าเลขที่ป้อนเป็นเลขอาร์มสตรองหรือไม่

เลขอาร์มสตรองคืออะไร?

เลขที่เท่ากับผลรวมของเลขยกกำลังสามของตัวเลขแต่ละหลัก เช่น 153 = 1³ + 5³ + 3³ = 1 + 125 + 27 = 153

ตัวอย่าง: 153, 371, 1634, ...

โปรแกรม

#include <stdio.h>
int main() {
    int number, remainder, total = 0, temp;
    printf("enter the number: ");
    scanf("%d", &number);
    temp = number;
    while (number > 0) {
        remainder = number % 10;
        total = total + (remainder * remainder * remainder);
        number = number / 10;
    }
    if (temp == total)
        printf("This number is Armstrong number");
    else
        printf("This number is not Armstrong number");
    return 0;
}

ผลลัพธ์

enter the number = 371
This number is Armstrong number
Check: 371 = 3*3*3 + 7*7*7 + 1*1*1 = 27 + 343 + 1 = 371

enter the number = 53
This number is not Armstrong number
Check: 53 = 5*5*5 + 3*3*3 = 125 + 27 = 152 != 53