c - 我的递归质数函数代码有一些错误

标签 c recursion goto

我应该输入一个正数,终端应该打印它是否为质数。它还应该要求用户重复输入一个数字,直到用户按下“q”。它在没有 goto 循环的情况下工作正常,即一次一个。

有人能告诉我我的代码有什么问题吗?

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

prime(int a, int b) {
  if (a == 1) {
    printf("neither prime nor composite\n");
    return;
  } else if ((a % b) == 0) {
    printf("composite no.\n");
    return;
  } else if (b >= a) {
    printf("prime no.\n");
    return;
  } else
    prime(a, (b + 1));
}

main(void) {
  int x, y = 0, z;
  char a[10], b;
  loops: printf("enter an integer:\t");
  do {
    b = getchar();
    if (b == 'q')
      exit(1);
    x = atoi(&b);
    y = (10 * y) + x;
  } while (b != '\n');
  z = y / 10;
  printf("num is %d and it's\t", z);
  prime(z, 2);
  goto loops;
  return 0;
}

最佳答案

您没有在循环开始时将 y 初始化为 0

关于c - 我的递归质数函数代码有一些错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21636243/

相关文章:

c++ - goto 对 C++ 编译器优化的影响

Sql - goto 语句

c99 转到过去的初始化

c - 如何使用 C 定义带有变量的数组?

c - 有没有办法_完全_避免缓存未命中?

c - for循环中的内存泄漏

javascript - 在javascript中从数组中删除对象元素

c - 管理客户端进程分配的资源

javascript - 递归函数 指数函数

Ruby递归替换数组