我在制作一个程序时遇到了一些麻烦。每次我尝试编译它时,我都会遇到Segmentation Fault 11.我不知道为什么会这样。我正在使用Code Block IDE,每当我构建和运行时,分段故障11继续出现。关于如何解决这个问题的任何想法?
#include <stdio.h>
#define NUMTEMPS 2881
int main(void){
//opening the file with temperatures
FILE * ifp;
ifp = fopen("temp.txt", "r");
//Declaring variables
int i,j;
int pct, num30 = 0, count_ac_h = 0, count_ac_t = 0, current_h = 0;
int ac_on = 0, count_ac = 0;
double temps[2881], pct_hr[24], diff, current_temp, previous_temp;
//Checking the temperature from the .txt file and counting the occurences
for (i = 0; i < 2881; ++i){
fscanf(ifp, "%lf", &temps[i]);
}
previous_temp = temps[0];
for (i = 0; i < 2881; ++i){
if (num30 == 120){
count_ac_t += count_ac_h;
pct_hr[current_h] = (double)(count_ac_h/120);
current_h++;
count_ac_h = 0;
num30 = 0;
}
current_temp = temps[i];
diff = previous_temp - current_temp;
if(diff > -0.5 && diff <0.5){
if(ac_on == 1){
count_ac_h++;
}
}
else if (diff <= -0.5){
if (ac_on == 0){
ac_on = 1;
count_ac_h++;
}
}
else if (diff >= 0.5){
if(ac_on == 1)
ac_on = 0;
}
num30++;
previous_temp = current_temp;
}
// Creating the bar graph based on results from above
double pct_day = (double)(count_ac/NUMTEMPS);
for (i = 20; i >= 0; i--){
pct = i*5;
for (j = 0; j < 24; ++j){
if (pct > (pct_hr[j]*100))
printf("_");
else
printf("*");
}
printf("\n");
}
return 0;
}
答案 0 :(得分:3)
for (i = 20; i >= 0; i--){
pct = i*5;
for (i = 0; i < 24; ++i){
if (pct > (pct_hr[j]*100))
printf("_");
else
printf("*");
}
检查此循环,对嵌套循环使用不同的循环变量。这里j
未初始化,因此如果它采用随机大值,则会导致分段错误。
答案 1 :(得分:1)
这一行:
pct_hr[current_h] = (double)(count_ac_h/120);
您如何确定current_h
永远不会超过23?