为什么我的打印质数的代码提前终止?

问题描述 投票:1回答:2

我试图用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后,程序终止。有想法吗?谢谢。

c algorithm for-loop logic primes
2个回答
0
投票

这里是程序的可能的固定版本。


0
投票

使用此代码:-

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.