【问题标题】:Why does my code to print prime numbers terminate early?为什么我打印素数的代码会提前终止?
【发布时间】:2020-09-30 19:09:15
【问题描述】:

我尝试用 C 编写程序来打印从 2 到给定数字的所有素数。

#include <stdio.h>
#include <math.h>

int main() {
    int up, t = 1, i, j;
    puts("This program will show you a list of all prime numbers from 2 to the number you enter below: ");
    scanf("%d", &up);
    for(i == 2; i <= up; i++) {
        for(j == 1; j <= sqrt(i); j++) {
            if(i % j != 0) {
                t = 0;
            }
            if(t == 1) {
                printf("%d", i);
            }
        }
    }
    return(0);
}

返回以下结果:

$ gcc prime.c -lm
$ ./a.out

This program will show you a list of all prime numbers from 2 to the number you enter below: 
10

我的意思是,在我输入 10 之后,程序就会终止。 想法? 谢谢。

【问题讨论】:

  • i == 2 你从哪里学来的?
  • 这个if(t == 1) {..} 应该在内部循环之后。
  • ...和t 应该在j 循环开始之前初始化。您也可以在找到除数后立即从内循环中break
  • 总是向编译器请求警告并注意它们。这会发现你的两个问题。 (我使用-Wall -Wextra -pedanticgcc。)
  • @ikegami 我一开始就指定了 t = 1。非常感谢您的警告想法。

标签: c algorithm for-loop logic primes


【解决方案1】:

这是您程序的一个可能的固定版本。

注意,除法应该从 2 开始,而不是 1。

    #include <stdio.h>
    #include <math.h>

    int main() {
        int up, i, j;
        int prime;

        puts("This program will show you a list of all prime numbers from 2 to the number you enter below: ");
        scanf("%d", &up);
        for(i = 2; i <= up; i++) {
            prime = 1;
            for(j = 2; j <= sqrt(i); j++) {
                if(i % j == 0) {
                  prime = 0;
                }
             }
            if (prime == 1)
              printf("%d ", i);
        } 
        printf("\n");
        return(0);
    }

例子:

$ ./prime
This program will show you a list of all prime numbers from 2 to the number you enter below: 
10
2 3 5 7 

【讨论】:

    【解决方案2】:

    使用此代码:-

    #include <stdio.h>
    
    int isprime(int num){
        int loop; /* loop variable */
        for(loop=2;loop<num;++loop){
            if(num % loop==0){
                return 0;
            }
        }
        return 1;
    }
    
    int main(){
        puts("This program will show you a list of all prime numbers from 2 to the number you enter below: ");
        int up;
        scanf("%d", &up);
        if (isprime(up)){
            printf("It is a prime number\n");
        } else{
            printf("It is not a prime number\n");
        }
        return(0);
    }
    

    看起来你是个学生。您正在使用 == 这是一个比较运算符。您必须在循环中使用 =。了解更多。

    【讨论】:

      猜你喜欢
      • 2016-07-13
      • 2013-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-05
      相关资源
      最近更新 更多