在计算圆[3] [6]时,程序似乎在第54行崩溃。可能是什么导致了这个?我输入了一堆打印语句来查找一些信息,所有内容似乎都很好,直到完全[3] [6],这似乎没什么特别的,因为它崩溃了。
int main() {
double a, b, circleXMax, circleYMax, circleRMax;
double rand_float(double a, double b);
int i, j;
int circleInfo = 3;
int circleNum = 50;
int PI = 3.14;
double circleArea;
double circleAreaMax = 0;
double circles[circleInfo][circleNum];
printf("Opened \n");
for(i = 1; i <= circleNum; i++) {
printf("Start of i = %d \n", i);
for(j = 1; j <= circleInfo; j++) {
printf("Start of j = %d \n", j);
if(j == 1 || j == 2) {
printf("Start of randomization of j (%d) \n", j);
circles[j][i] = rand_float(100.00, 900.00);
printf("circles[%d][%d] = %f \n", j, i, circles[j][i]);
}
else {
printf("Start of randomization of j (%d) \n", j);
circles[j][i] = rand_float(0.00, 100.00);
printf("circles[%d][%d] = %f \n", j, i, circles[j][i]);
}
}
printf("Start of calculation of circleArea \n");
circleArea = PI * circles[3][i] * circles[3][i];
printf("Completed calculation of circleArea = %f \n", circleArea);
if(circleArea >= circleAreaMax) {
printf("circle was larger then maximum current \n");
circleAreaMax = circleArea;
circleXMax = circles[1][i];
circleYMax = circles[2][i];
circleRMax = circles[3][i];
} else {
printf("circle was NOT larger then maximum current \n");
}
}
printf("Circle with largest area (%f) has\n", circleAreaMax);
printf("center (%f, %f) and radius %f", circleXMax, circleYMax, circleRMax);
}
double rand_float(double a, double b) {
printf("doing a randomization via rand_float \n");
return (((double)rand()/RAND_MAX)*(b-a))+a;
}
说完后崩溃了:
“j = 3的开始”
“开始随机化j(3)”
“通过rand_float进行随机化”
答案 0 :(得分:5)
我注意到的问题是循环边界。两种情况
for(i = 1; i <= circleNum; i++)
和
for(j = 1; j <= circleInfo; j++)
C数组具有基于0的索引,因此对于定义为<type> arr[m][n]
的数组,最高可能的有效索引将为arr[m-1][n-1]
。
那说了一些其他评论:
main()
内有函数声明,它们需要在文件范围内才能对整个翻译单元可见。否则只有main()
和它们之后定义的函数才能获得它们的声明。int main()
应为int main(void)
,以使托管环境符合标准(除非您使用明确定义前者的专用环境为有效签名)。