我需要编写一个程序来完成所有 3 件事:打印所有因子,对因子求和,并检查它是否是一个完美的数字。
我应该只使用 while 循环,但我无法让它工作,所以我使用了一些 For 循环。除此之外,我遇到的主要麻烦是让程序检查数字是否完美。
例如,我输入“6”,得到因子 1、2、3、6,总和 = 12,但程序认为“6”不是一个完美的数字。请查看我的代码,看看我哪里出错了。
#include <stdio.h>
int main(void) {
int n, f, sum;
f = 1;
sum = 0;
printf("Enter number: ");
scanf("%d", &n);
printf("The factors of %d are:\n", n);
//Finding the factors of the given number
while (f <= n) {
if (n % f == 0) {
printf("%d\n", f);
}
f++; //f++ is the same as f = f + 1
}
//Finding the sum of the factors
for (f = 1; f <= n; f++) {
if (n % f == 0) {
sum = sum + f;
}
}
printf("Sum of factors = %d\n", sum);
//Checking if the number is perfect or not; A number is considered perfect if the sum of it's divisiors equal the number eg 6 = 1+2+3
for (f = 1; f < n; f++) {
if (n % f == 0) {
sum = sum + f;
}
}
if (sum == n) {
printf("%d is a perfect number\n", n);
} else {
printf("%d is not a perfect number\n", n);
}
return 0;
}