我正在解决教科书问题,我在下面编写了这段代码来识别用户输入的正数下面的所有素数:
#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/