在C語言中,要設計一個isPerfect函式來判斷一個數字是否為完美數是相對直接的。完美數的定義是一個正整數,它等於其所有正除數(本身除外)之和。例如,6是一個完美數,因為其正除數1、2和3的和恰好是6。
以下是isPerfect函式的一個實現,該函式接受一個整數x作為輸入,如果x是完美數,則返回1;如果不是,則返回0。
c
Copy code
#include <stdio.h>
// 函式原型宣告
int isPerfect(int x);
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
if (isPerfect(number)) {
printf("%d is a perfect number.\n", number);
} else {
printf("%d is not a perfect number.\n", number);
}
return 0;
}
// 定義 isPerfect 函式
int isPerfect(int x) {
int sum = 0;
// 計算所有小於 x 的正因數之和
for (int i = 1; i < x; i++) {
if (x % i == 0) {
sum += i;
}
}
// 如果該和等於 x,則 x 是完美數
if (sum == x) {
return 1;
} else {
return 0;
}
}
在這個實現中,isPerfect函式通過一個for循環迭代1到x-1的所有數字,檢查每個數字是否是x的正除數(即x % i == 0)。如果是,則將該數字加到sum變量上。迭代完成後,如果sum等於x,則x是一個完美數,函式返回1;否則,返回0。