我正在做家庭作业,以计算用户选择的第n个素数.我有这个工作得很好,并且相当快,但我决定添加一个错误消息,如果用户输入任何大于50000.由于某种原因,这决定不工作,所以我把它拿出来.之后,一旦用户输入他们想要的素数,我的程序就会冻结.
#include <stdio.h>
int main(void)
{
long int pFactor,test,nthCount,target,result,notPrime;
test=2;
nthCount=0;
printf("Which prime number do you want to know?");
scanf("%li",&target);
while (nthCount<target)
{
for(pFactor=test/2;pFactor>1;pFactor--)
{
notPrime=0;
result=(test%pFactor);
if(result==0)
{
notPrime=1;
break;
}
if(notPrime!=1)
{
nthCount++;
notPrime=0;
test++;
}
}
}
test--;
printf("The %li prime number is %li.\n",target,test);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我认为这是与scanf相关的东西,因为我试图打印之后的任何东西都没有出来.
for(pFactor=test/2;pFactor>1;pFactor--) // where test = 2
Run Code Online (Sandbox Code Playgroud)
推导出,pFactor> 1总是假的(1> 1)
因此,流量永远不会进入for循环,因此nthCount始终保持不变0.
while (nthCount<target) // becomes an infinite loop
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
975 次 |
| 最近记录: |