实际应用中经常会用到二维平面上的点,点的操作包括设置点的位置( pointT setPoint(double x , double y ) ),显示第n个点的位置( void showPoint(pointT *p,int n) ), 计算两个点的距离double distPoint(pointT pt1, pointT pt2),并将点的坐标以及距离保存到文件Info.txt中void saveInfo (pointT pt1, pointT pt2, char *filename) 。试定义平面上点的数据类型pointT,并实现这些函数,自行编写main函数测试这些函数。
#include<stdio.h>
#include<math.h> struct pointT{
double x;
double y;
}; struct pointT setPoint(double x, double y)
{
struct pointT temp; temp.x = x;
temp.y = y;
return temp;
} void showPoint(struct pointT *p, int n)
{
printf("point%d(%.1f , %.1f)", n, (p+n-)->x, (p+n-)->y);
} double distPoint(struct pointT pt1, struct pointT pt2)
{
return sqrt((pt1.x - pt2.x)*(pt1.x - pt2.x) + (pt1.y - pt2.y)*((pt1.y - pt2.y)));
} void saveInfo(struct pointT pt1, struct pointT pt2, char *filename)
{
//打开文件
FILE *fp;
fp = fopen(filename , "a"); //操作
fprintf(fp, "point1(%.1f , %.1f), point2(%.1f , %.1f)\n", pt1.x, pt1.y, pt2.x, pt2.y);
fprintf(fp, "dist between point1 and point2 is %.1f\n", distPoint(pt1 , pt2)); //关闭文件
fclose(fp);
} // test
int main()
{
struct pointT pt[]; pt[] = setPoint( , );
pt[] = setPoint( , );
pt[] = setPoint( , ); showPoint(pt , ); printf("dist between point1 and point2 is %.1f\n", distPoint(pt[] , pt[])); char *filename = "Info.txt";
saveInfo(pt[], pt[], filename); return ;
}
补充说明:
代码是按c89写的,这个标准里必须使用
struct pointT pt1
声明,而不能使用
pointT pt
如果必要,自行修改。
(本人用的编译器比较旧)