c - 完美号码检查

标签 c function scope

所以我的代码背后的想法是创建一个程序,该程序使用函数来检查和打印 1 到 1000 之间的所有完美数字。我想出了这个,但问题是没有打印任何东西。它成功构建、运行并退出。

我已经检查了我的代码 3-4 次,但我找不到逻辑上的差距,所以我认为这是一个变量定义问题,与某些函数的作用域有关。任何人都会对为什么我的程序无法识别完美数字然后打印它有任何意见吗?

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

/*
 * 
 */

void perfectNumCheck(int num);
void perfectNumPrint (int perfectNum);

int main(void) {

    int i;
    for (i = 1; 1 <= 1000; i++)
        perfectNumCheck(i);

}

void perfectNumCheck(int num) {

    int i;
    int temp = 0;

    for (i = 0; i < num; i++) {
        if (num % i == 0)
            temp += i;
    }

    if (temp == num)
        perfectNumPrint(num);

}

void perfectNumPrint(int perfectNum) {

    int i;
    for (i = 0; i < perfectNum; i++) 
        if (perfectNum % i == 0) 
            printf ("%d, ", i);

    printf("are factors of the perfect number %d.\n", perfectNum);

}

最佳答案

这里有错字:

for (i = 1; 1 <= 1000; i++)
    perfectNumCheck(i);

应该是

for (i = 1; i <= 1000; i++)
    perfectNumCheck(i);

此外,您要除以零。将 for 循环中的所有 i = 0 更改为 i = 1

关于c - 完美号码检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30764665/

相关文章:

r - 从函数值有效地创建矩阵

c - 如何在C中添加多个重复的总数?

c - Valgrind 和全局变量

c++ - 我如何使用 cryptimportkey 函数导入私钥来加密数据相同的结果使用导入的 key

javascript - 无法在 image.onload 内生成输出

postgresql - 如何将变量传递给 postgresql 中的 date_part 函数?

c++ - 文件作用域和静态 float

JavaScript:命名空间与作用域

javascript - 对象中的函数和对 'this' 属性的访问 - 失败

c - 这会导致溢出吗?