1

我需要编写一个程序来完成所有 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;
}
4

2 回答 2

2

看看你在哪里声明 f,以及你第一次在哪里使用它。大约一英里的距离。那很糟。

现在看看你在哪里声明 sum,以及你第一次在哪里使用它。更糟。现在为什么你的代码不起作用:看看你第二次认为你第一次使用“sum”的地方。除非你没有。

通过将初始化与变量的实际使用相距甚远,您不仅使您的代码不可读,而且您实际上通过使用 sum 相信它的值为零,而实际上却是自取其辱。

于 2016-04-05T07:46:36.483 回答
1
for (i = 0; i < n; i++) {
  statement;
}

可以写成:

i = 0;
while (i < n) {
  statement;
  i++;
}
于 2016-04-05T07:50:54.347 回答