如何从以下代码中删除 goto?
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
bool is_prime(unsigned num)
{
if(num==0 || num==1)
return false;
if(num==2)
return true;
for(unsigned i=2;i<=num-1;i++)
if(num%i==0)
goto step;
return true;
step: return false;
}
int main(void)
{
unsigned n;
printf("enter the number: ");
scanf("%u",&n);
printf("%u\n",is_prime(n));
return 0;
}
最佳答案
将其替换为 return false;
。 return
退出函数。代码甚至已经依赖于该行为。
bool is_prime(unsigned num)
{
if(num == 0 || num == 1)
return false;
for(int i = 2; i < num - 1; i++)
if(num % i == 0)
return false;
return true;
}
关于C 循环和转到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19068994/