我正在做的一个程序出了点问题。每次我尝试编译它的时候,我都会遇到分割错误11。我不知道为什么会发生这种情况。我正在使用代码块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;
}发布于 2014-03-20 03:20:51
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是未初始化的,所以如果随机取大值,就会导致分割错误。
发布于 2014-03-20 03:22:18
这一行:
pct_hr[current_h] = (double)(count_ac_h/120);你怎么能确定current_h永远不会大于23?
https://stackoverflow.com/questions/22515954
复制相似问题