[英]C program giving incorrect output
I am writing a C program to sum up prime numbers below a certain limit (9 for now).我正在编写一个 C 程序来总结低于某个限制(目前为 9)的质数。
I expect 17 but the compiler gave me an unexpected output of 32781.我期望 17,但编译器给了我一个意外的 output of 32781。
#include <stdio.h>
#include <stdbool.h>
bool isprime(int n);
int main(){
const int LIMIT=9;
int sum;
for (int j=1;j<LIMIT;j++){
if (isprime(j)){
sum+=j;
}
}
printf("%d",sum);
return 0;
}
bool isprime(int n){
if (n<=1){
return false;
}
else{
for(int i=2;i<n;i++){
if (n%i==0){
return false;
break;
}
}
return true;
}
}
Does anyone understand why this happened?有谁明白为什么会这样?
You declarred int sum;
你声明了
int sum;
but didn't give sum a starting value, so it's basically reading garbage from memory. In c you need to initialize your variables properly.但没有给 sum 一个起始值,所以它基本上是从 memory 中读取垃圾。在 c 中,您需要正确初始化变量。
int sum = 0;
should fix the problem.应该解决问题。
If you are using clang as your compiler, compiling using -Wall should warn you about this.如果您使用 clang 作为编译器,使用 -Wall 进行编译应该会警告您这一点。
Local variables are not initialized, so you need to initialize at declaration or before use.局部变量没有被初始化,因此需要在声明时或使用前进行初始化。
int sum = 0;
or...或者...
int sum;
for (sum = 0; bla; bla)
If the variable had been declared globally (outside of any function... main is a function) it will automatically initialize to 0.如果该变量已全局声明(在任何 function 之外... main 是一个函数),它将自动初始化为 0。
#include <stdio.h>
int a;
int main(void)
{
int b;
printf("%d\n%d\n", a, b);
return 0;
}
Variable 'a' will be 0 and 'b' will be garbage because it's an uninitialized local variable.变量“a”将为 0 而“b”将是垃圾,因为它是一个未初始化的局部变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.