平面上の点を表すのにpointという構造体を定義してみましょう。 x座標、y座標ともdouble型とします。
struct point {
double x;
double y;
};
などと定義します。さらに、3点を頂点とする三角形は次のように定義されます。
struct triangle {
struct point a;
struct point b;
struct point c;
};
構造体を使って次の問題を解くプログラムを作ってみましょう。
「平面上の2点のx座標、y座標を入力して、 この2点間の距離を求めよ」
このプログラムを作るには、以下のことを行えばよいです。
#include< math.h >
struct point {
double x;
double y;
};
void inpdata(struct point *p, int j)
{
printf("点%dのx座標を入力してください \n", j);
scanf("%lf", &(p->x));
printf("点%dのy座標を入力してください \n", j);
scanf("%lf", &(p->y));
}
double measure(struct point p0, struct point p1)
{double r;
r=sqrt((p0.x - p1.x)*(p0.x - p1.x) + (p0.y - p1.y)*(p0.y - p1.y));
return (r);
}
main()
{
int i;
double dist;
struct point po[2];
for(i=0; i<2;++i){inpdata(&po[i], i);}
dist=measure(po[0], po[1]);
printf("二点(%lf, %lf), (%lf, %lf)の距離は,%lfです。\n", po[0].x, po[0].y, po[1].x, po[1].y, dist);
}
上のプログラムは、
関数inpdataの引数は、構造体で、ポインタの形で渡されます。
関数measureの引数は、構造体ですが、普通の形で渡されています。返り値は、 double型になっています。
ポインタの形で渡されるかいなかによって、 関数内での参照のされかたが異なりますので、気をつけてください。
#include< math.h >
struct point {
double x;
double y;
};
void inpdata(struct point *p, int j)
{
printf("点%dのx座標を入力してください \n", j);
scanf("%lf", &(p->x));
printf("点%dのy座標を入力してください \n", j);
scanf("%lf", &(p->y));
}
double measure(struct point *p0, struct point *p1)
{double r;
r=sqrt((p0->x - p1->x)*(p0->x - p1->x) + (p0->y - p1->y)*(p0->y - p1->y));
return (r);
}
main()
{
int i;
double dist;
struct point po[2];
for(i=0; i<2;++i){inpdata(&po[i], i);}
dist=measure(&po[0], &po[1]);
printf("二点(%lf, %lf), (%lf, %lf)の距離は,%lfです。\n", po[0].x, po[0].y, po[1].x, po[1].y, dist);
}
上記二つのプログラムは、文法的に完全に正しいプログラムです。
関数の呼出し方法、関数内での参照の方法等、違いを理解してください。