c - 完全数逻辑检查

标签 c

我正在编写一个代码来打印给定范围内的所有完美数字。 我对我的代码进行了试运行。但我没有得到预期的输出。

#include<stdio.h>
void perfect(int,int);
int main()
{
    int start,end;

    printf("Enter range");
    scanf("%d%d",&start,&end);

    perfect(start,end);
    return 0;
}

void perfect(int s,int e)
{
    int i=0,j=0,sum=0;
    for(i=s;i<=e;i++)
    {
        for(j=1;j<i;j++)
        {
            if(i%j==0)  //i contains the number in range
            {
            sum=sum+j;
            }
        }

        if(sum==i)   // if sum of all factors of the number is equal to the number then its perfect number
        {
            printf("%d",i);

        }

        }

    }

输入:1 10 无可见输出。 预期输出:6

最佳答案

在进入外循环之前将sum初始化为0,但在启动内循环时没有清除它。对于您要测试的每个数字,您需要从总和 0 开始。

int i=0,j=0,sum=0;
for(i=s;i<=e;i++)
{
    sum = 0;
    for(j=1;j<i;j++)
    {
        ...

关于c - 完全数逻辑检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42772623/

相关文章:

c - 此线程代码中在哪里生成段错误?

c - N 个未知键的最小完美散列

c - 在 Linux 上以编程方式获取有关 ROM 内存类型和大小的信息

用于 C 风格向下转型的 C++ 转型

c - "the"C 标准是否指定编译器必须遵守哪个标准?

gcc 可以对未知的迭代次数进行循环优化( strip 挖掘/阻塞)吗?

c - 如何设置 Travis 来构建 Arduino/Spark/Teensy 库

c - 警告 : cast to pointer from integer of different size [-Wint-to-pointer-cast] c programming

c++ - 我的 do while 循环只执行一次

c - 如何在词法分析过程中检测字符串?