C 编程:使用关系运算符 - 小于与小于等于
C Programming: Using Relational Operators - Less than vs less than equals
我正在解决一个教科书问题,我在下面编写了这段代码来识别用户输入的正数下方的所有质数:
#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 . . .
现在,质数不再打印,但我想不出任何合乎逻辑的原因。我的大脑现在因为想到这应该有效的可能原因而受伤。请帮忙。谢谢!
我在 codeblocks 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;
语句为真因此没有输出产生
我正在解决一个教科书问题,我在下面编写了这段代码来识别用户输入的正数下方的所有质数:
#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 . . .
现在,质数不再打印,但我想不出任何合乎逻辑的原因。我的大脑现在因为想到这应该有效的可能原因而受伤。请帮忙。谢谢!
我在 codeblocks 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;
语句为真因此没有输出产生