C编程: Using Relational Operators - Less than vs less than equals

标签 c for-loop relational-operators

我正在解决教科书问题,我在下面编写了这段代码来识别用户输入的正数下面的所有素数:

#include <stdio.h>

int main(void)
{
    int j, input, notaprime;

    scanf_s("%d", &input);

    printf("List of prime numbers:\n");
    for (; input >= 2; input--)
    {
        notaprime = 0;
        for (j = 2; j < input; j++) //OR (for(j = 2; j*j <= input; j++)
        {
            if ((input % j) == 0)
            {
                notaprime = 1;
                break;
            }
            else
            {
                ;
            }
        }

        if (notaprime)
        {
            ;
        }
        else
        {
            printf("%d\n", input);
        }
    }

    return 0;
}

当输入 30 时,输出如下:

30
List of prime numbers:
29
23
19
17
13
11
7
5
3
2
Press any key to continue . . .

但是,当我将内部 for 循环中的关系运算符更改为:

        for (j = 2; j < input; j++)

至:

        for (j = 2; j <= input; j++) //Changed from less than to less than equals

以下成为输入值30的输出:

30
List of prime numbers:
Press any key to continue . . .

现在,素数不再打印,但我想不出任何合乎逻辑的原因。现在我的大脑因思考为什么这应该是有效的可能原因而感到疼痛。请帮忙。谢谢!

我在代码块 16.01 和 Visual Studio Community 2015 上尝试过此操作。输出是相同的。

最佳答案

您的代码中存在逻辑错误

我们知道质数是除以 1 或它本身的数

当你这样做时for (j = 2; j < input; j++)然后您检查以下所有数字 input这是正确的。

但是当你这样做时for (j = 2; j <= input; j++)您查看 input .

因为每个数字都被自己除(input % j) == 0每次,notaprime = 1;陈述为真,因此没有产生输出

关于C编程: Using Relational Operators - Less than vs less than equals,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41486202/

相关文章:

c++ - block 内变量的生命周期是多少?

c++ - 以零开头的数字有什么特别之处?

python - 如何使用python转换csv文件中文件夹中的多个xml文件?

c++ - 具有两个关系运算符的单个变量如何在内部工作

c - 直接将左移运算的结果赋值给一个变量和C中的左移赋值运算有什么区别?

c - 比较两个指针有什么限制?

c - 当我尝试读取十六进制文件时,C 代码出现段错误

c - 在 C 中将 GTK 小部件调整到 vbox

java - 形式为: "for (A b : c)" in Java的for循环

Javascript:事件监听器中未定义 event.target.id