如何在 C 中使用重启选项进行质数检查?

  • 本文关键字:选项 重启 c
  • 更新时间 :
  • 英文 :


我做了一个程序来检查一个数字是否是质数。

该计划一开始运作良好。当程序开始时,我包括了一个质数,它给了我正确的答案。当我使用"是"选项重新启动程序并给它一个非质数时,它也给了我正确的答案。但是,当我使用"yes"选项再次重新启动程序时,即使输入是质数,返回的数字都不是素数。

你能告诉我我的代码中的任何错误吗?

这是我的代码

#include <stdio.h>
#include <ctype.h>
int main(void) 
{
int i=0, number, count=0;
char answer;
printf("nnthis programm check if a nummber is a prime nummbernn");
do 
{     
printf("input a positive nummber: ");
scanf("%d", &number);
for (i=2; i<=number/2; i++) 
{   

if(number%i==0)
{
count=1;
break;            
}
}
if (count==0)
{ 
printf("n%d is  prime nummber.nn",number);
}
else if (count==1)
{ 
printf("n %d is not prime nummber.nn",number);
}
do
{ 
printf("Do you want to restart the programm (J/N)? ");
scanf(" %c", &answer);
answer=toupper(answer);
} while (answer!='J' && answer!='N');
} while (answer=='J');

return 0;
}

修复非常简单:只需在外部do{}while()循环主体的开头添加count = 0。如果您忘记重置此count变量,那么您之前循环迭代会产生历史效果。

请使用以下代码:

#include <stdio.h>
#include <ctype.h>
int main(void) 
{
int i=0, number=0, count=0;
char answer;
printf("nnthis programm check if a nummber is a prime nummbernn");
do 
{     
printf("input a positive nummber: ");
scanf("%d", &number);
for (i=2; i<=number/2; i++) 
{   

if(number%i==0)
{
count=1;
break;            
}
}
if (count==0)
{ 
printf("n%d is  prime nummber.nn",number);
}
else if (count==1)
{ 
printf("n %d is not prime nummber.nn",number);
}
do
{ 
printf("Do you want to restart the programm (J/N)? ");
scanf(" %c", &answer);
answer=toupper(answer);
count=0;
} while (answer!='J' && answer!='N');
} while (answer=='J');

return 0;
}

我希望它能解决您的问题

最新更新