我有一个50个指针的数组,指向包含x和y中心坐标以及圆的半径的圆形结构。我分配了所有内存,并使用rand_float
为圆圈创建随机x,y和z。我的计划的关键是找到面积最大的圆圈并将其打印出来。我遇到了我的程序问题,我知道随着rand结果不会每次都是一样的,但我的价值是没有接近预期的输出。我也没有在输出中看到来自largestcircle
的printf
输出。最后,当我尝试使用free(circleptr
运行程序时,我收到一个错误)。指向圆的指针的数组struct
#include <stdio.h>
#include <stdlib.h>
#define PI 3.14
double rand_float(double a,double b){ //function provided my teacher.
return ((double)rand()/RAND_MAX)*(b-a)+a;
}
struct circle{
double x;
double y;
double z;
};
void largestcircle(struct circle **circleptr){
float max = 0, radius =0, x= 0, y=0;
int i;
for(i = 0; i<50; i++){
if(circleptr[i]->z *circleptr[i] ->z *PI > max){
max = circleptr[i]->z*2*PI;
radius = circleptr[i]->z;
x = circleptr[i] ->x;
y = circleptr[i] ->y;
}
}
printf("Circle with largest area (%f) has center (%f, %f) and radius %f\n", max,x,y,radius);
}
int main(void) {
struct circle *circleptr[50];
//dynamically allocate memory to store a circle
int i;
for(i=0; i<50; i++){
circleptr[i] = (struct circle*)malloc(sizeof(struct circle));
}
//randomly generate circles
for(i=0; i<50; i++){//x
circleptr[i]->x = rand_float(100, 900);
circleptr[i]->y = rand_float(100, 900);
circleptr[i]->z = rand_float(0, 100);
//printf("%11f %11f %11f \n", circleptr[i] ->x, circleptr[i]->y, circleptr[i]->z);
}
largestcircle(circleptr);
for(i=0; i<50; i++){
free(circleptr[i]);
}
return 0;
}
输出应该是这个样子:
Circle with largest area (31380.837301) has center (774.922941,897.436445) and radius 99.969481
我当前的X,Y和Z值的样子:
1885193628 -622124880 -622124884
1885193628 -622124868 -622124872
1885193628 -622124856 -622124860
1885193628 -622124844 -622124848
1885193628 -622124832 -622124836
1885193628 -622124820 -622124824
1885193628 -622124808 -622124812
1885193628 -622124796 -622124800
1885193628 -622124784 -622124788
1885193628 -622124772 -622124776......etc.
的思考?
你不要叫'largestcircle'。那么你如何看待printf? – Arash
'max = circleptr [i] - > z * 2 * PI;'这不是一个圆的面积公式。应该是'max = circleptr [i] - > z * circleptr [i] - > z * PI;'。并建议你使用比'z'更好的变量名称 - 'radius'会更有意义。 – kaylum
'免费(circleptr)'当然你不能那样做。你在哪里有'circleptr = malloc()'?无处。所以如果你没有分配这个指针,你就不能释放它。用'free(circleptr [i])'尝试循环。 – kaylum