请帮我找错误 - 程序显示素数

时间:2015-05-13 21:46:26

标签: c

我正在学习C,你能帮我找到我程序中的错误吗? 我从书中重新输入了代码,但我仍然不知道我的错误在哪里。 我尝试使用https://www.diffchecker.com/diff,但我没有看到任何逻辑差异。我放弃。 你能帮帮我吗?

我的代码:

//ex7_9.c
#include <stdio.h>
#include <stdbool.h>

int main(void){

    int num;
    int limit;
    int div;
    bool isPrime;

    printf("Please insert your number: ");
    while((scanf("%d", &limit) == 1) && limit > 0){
        if(limit > 1)
            printf("Here are prime numbers up to %d limit\n", limit);
        else
            printf("Change limit - to bigger than one\n");

        for(num=2; num <= limit; num++){
            for(div=2, isPrime=true; (div*div) <=num; div++){

                if(num % div ==0)
                    isPrime = false;

                if(isPrime)
                    printf("%d is prime \n",num);

            }
        }
    }

    return 0;
}

正确的代码:

//ex7_9.c
#include <stdio.h>
#include <stdbool.h>

int main(void){

    int limit;
    int num;
    int div;
    bool numIsPrime;

    printf("Enter a positive integer: ");
    while (scanf("%d", &limit) == 1 && limit > 0){
        if (limit > 1)
            printf("Here are the prime numbers up through %d\n", limit);
        else
            printf("No primes.\n");
        for (num = 2; num <= limit; num++)
        {
            for (div = 2, numIsPrime = true; (div * div) <= num; div++)
                if (num % div == 0)
                    numIsPrime = false;
            if (numIsPrime)
                printf("%d is prime.\n", num);
        }
        printf("Enter a positive integer (q to quit): ");
    }
    printf("Done!\n");
    return 0;
}

来自我的代码:

Please insert your number: 10
Here are prime numbers up to 10 limit
5 is prime 
7 is prime 
9 is prime 

1 个答案:

答案 0 :(得分:2)

您在内循环上添加了括号。

您的代码是

for(num=2; num <= limit; num++){
    for(div=2, isPrime = true; div * div <=num; div++){
        if(num % div == 0)
        {
            isPrime = false;
        }
        if(isPrime)
        {
            printf("%d is prime \n",num);
        }
    }
}

而添加了明确括号的原文是

for (num = 2; num <= limit; num++)
{
    for (div = 2, numIsPrime = true; div * div <= num; div++)
    {
        if (num % div == 0)
        {
            numIsPrime = false;
        }
    }
    if (numIsPrime)
    {
        printf("%d is prime.\n", num);
    }
}

你的第二个if在内循环内;在原来它在外面。