圆形结构的指针数组

时间:2017-04-11 04:14:40

标签: c arrays pointers random struct

我有一个包含50个指针的数组,指向包含x和y中心坐标的圆结构,以及圆的半径。我分配了所有内存并使用rand_float为圈子创建随机x,y和z。我的程序的要点是找到面积最大的圆并打印出来。我遇到了我的程序问题,我知道每次rand结果都不一样,但我的值不在预期输出附近。我也没有在输出中看到printf的{​​{1}}输出。最后,当我尝试使用largestcircle)运行程序时收到错误。

free(circleptr

输出应该类似于:

#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;
}

我当前的x和z值如下所示:

Circle with largest area (31380.837301) has center (774.922941,897.436445) and radius 99.969481

思想?

3 个答案:

答案 0 :(得分:1)

当您打印circle->xcircle->y和{{1>时,您看到circle-&gt; x,y和z的一些垃圾随机值的问题与您的格式说明符有关。 }}。使用circle->z代替%f,因为您使用的是%d,而不是double

int

将上述内容更改为

printf("%d %d %d \n", circleptr[i]->x, circleptr[i]->y, circleptr[i]->z);

答案 1 :(得分:0)

以下是您的问题,您正在使用%d,请使用%llf

printf("%llf %llf %llf \n", circleptr[i] ->x, circleptr[i]->y, circleptr[i]->z);
printf("Circle with largest area (%llf) has center (%llf, %llf) and radius %llf\n", max, x, y, radius);

你可以在I而不是i获得空闲记忆

答案 2 :(得分:0)

此功能存在问题:

 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);
  }

if()语句与圆形区域* pie * r * r进行比较。 但是在if()中,max设置为圆的圆周,即2 * pie * r。

这会给你错误的答案。