溫馨提示×

c語言怎么用函數(shù)求水仙花數(shù)

小億
178
2023-12-29 20:29:24
欄目: 編程語言

水仙花數(shù)是指一個3位數(shù),其各位數(shù)字的立方和等于該數(shù)本身。下面是使用函數(shù)來求解水仙花數(shù)的示例代碼:

#include <stdio.h>

int isArmstrongNumber(int num) {
    int originalNum, remainder, result = 0;

    originalNum = num;

    while (originalNum != 0) {
        remainder = originalNum % 10;
        result += remainder * remainder * remainder;
        originalNum /= 10;
    }

    if (result == num) {
        return 1;
    } else {
        return 0;
    }
}

int main() {
    int num;
    printf("請輸入一個3位數(shù):");
    scanf("%d", &num);

    if (isArmstrongNumber(num)) {
        printf("%d 是水仙花數(shù)\n", num);
    } else {
        printf("%d 不是水仙花數(shù)\n", num);
    }

    return 0;
}

運行程序后,輸入一個3位數(shù),程序會判斷該數(shù)是否為水仙花數(shù)并輸出結(jié)果。

0