C 循环和转到

标签 c goto

如何从以下代码中删除 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/

相关文章:

c - 安装AVR开发平台for mac时架构x86_64错误

python - 使用 ctypes 从 C 结构数组到 NumPy 数组的高效转换

error-handling - VB6 出错时 GoTo Line x 或 Exit Do

c++ - 为什么在 constexpr 函数中不允许 goto?

c - 有多个 fork 和额外的打印品

c - 针对没有源代码的 .so 文件的 GCC 链接

c++ - C/C++ 中可中断的命名范围

c# - 如何在 C# 中一次跳出多个循环?

c - 将 char 数组分配给 union 数据类型时,我的编译器抛出错误 : "conversion from char* to non-scalar type"

c - 如何用 goto 翻译 if .. else 语句?