c - 如何编写 1 个 C 程序打印一个数的所有因数、因数之和并检查它是否为完美数

标签 c sum factors perfect-numbers

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

相关文章:

r - 如何根据 R 中因子的水平组合两个变量

java - Socket在同一台机器上的两个进程(起源于C和Java)之间进行通信

C:尝试从文件中读取浮点字符

javascript - 使用 javascript 在 html 中自动求和文本框

mysql - 与 where 条件相加相异连接

r - 按降序分组条形?

c - 如何在 Linux 中正确安装 gsl 库?

c - 使用 MSVC10 x64 解决缺乏内联 asm

ruby-on-rails - rails : sum all column elements where param1 == some value

r - 连接因子并替换 R 中的名称