我需要编写一个程序来完成所有 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;
}
最佳答案
看看你在哪里声明了f,又在哪里第一次使用了它。大约一英里的距离。那很糟。
现在看看你在哪里声明了 sum ,以及你第一次使用它的地方。更糟。现在为什么你的代码不起作用:看看你第二次想到你第一次使用“sum”的地方。除了你没有。
通过将初始化与变量的实际使用相距甚远,您不仅使您的代码不可读,而且您实际上是在搬起石头砸自己的脚使用 sum 相信它的值为零,而实际上它不是.
关于c - 如何编写 1 个 C 程序打印一个数的所有因数、因数之和并检查它是否为完美数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36419997/