我在其他程序中使用了 isPrime() 函数,它运行得很好,我什至之前也以同样的方式引用过它。由于某种原因,该程序中的功能无法正常工作。我使用 printf() 来检查函数返回的内容,它似乎是内存位置。但我不知道要更改什么,因为正如我所说,我确信该功能可以正常工作。
#include <stdio.h>
int main(void){
int isPrime(int a);
int result;
int x = 1;
while(x <= 1000){
result = isPrime(x);
if (result == 1){
printf("%d\n",x);
}
x++;
}
}
int isPrime(int a){
int count;
int z;
if(a == 1){
return 0;
} else {
for (z = a; z != 0; z-- ){
if(a % z == 0){
count++;
}
}
if(count <= 2){
return 1;
} else {
return 0;
}
}
}
最佳答案
将计数
初始化为0。
除此之外,在我的系统上它运行良好。
关于C 运行时错误(程序应该打印前 1000 个素数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15920552/