c - 如何计算素数

标签 c function recursion primes

我想要所有 Primes 并且程序可以运行,但我收到警告:

警告:控制到达非 void 函数的末尾 [-Wreturn-type] }

我知道我需要 bool isprim 中的最后一个return,但我不明白。

bool isPrim(int prim, int tester) {
    if (prim <= 1) {
        return 0;   
    } else if (tester == 1) {
        return 1;   
    } else if (tester >= 1 && (prim % tester) != 0) {
        isPrim(prim, tester - 1);
    } else if ((prim % tester) == 0) {
        return 0;   
    }
}   
    
int main() {
    int eingabe;
    int zaehler = 1;
    printf("Bitte Zahl zum testen eingeben\n");
    scanf("%i", &eingabe);

    if (isPrim(eingabe, eingabe - 1)) {
        printf("Ihre Zahl ist eine Primzahl\n");
    } else {
        printf("Ihre Zahl ist keine Primzahl\n");
    }
    //show me all Primes <1000
    printf("Nun werden alle Primzahlen bis 10000 ausgegeben\n\n");
    while (zaehler <= 10000) {
        if (isPrim(zaehler, zaehler - 1)) {
            printf("%i\t", zaehler);    
        }   

        zaehler++;  
    }

    return 0;
}

最佳答案

您不能有任何可能不返回 bool 值的分支,即使它们永远不会被执行:

// This will throw a warning.
bool func(){
  if( true ){
    return 0;
  }
}

要么将最后一个 else if 更改为 else,要么在最后添加一个额外的 else(或仅返回)。

关于c - 如何计算素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43610890/

相关文章:

java - 获取由 JNA 中的参数返回的不透明结构

java - 小端到整数(或 BigInteger)

python - Gstreamer 在 PLAYING 状态下更改源

python scipy fsolve 递归函数

c - 双向结构指针链接,C

c# - C# 中的 void* 替代方案

jquery - AJax不是函数错误

javascript - 如何动态获取执行另一个Function的Function Name?

c - 为什么我不能在 C 中返回递归函数的最后一个值?

javascript - 在递归中使用全局变量是一种好习惯吗