【发布时间】: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 -pedantic和gcc。) -
@ikegami 我一开始就指定了 t = 1。非常感谢您的警告想法。
标签: c algorithm for-loop logic primes