实际应用中经常会用到二维平面上的点,点的操作包括设置点的位置( 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-1)->x, (p+n-1)->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) ", pt1.x, pt1.y, pt2.x, pt2.y); fprintf(fp, "dist between point1 and point2 is %.1f ", distPoint(pt1 , pt2)); //关闭文件 fclose(fp); } // test int main() { struct pointT pt[3]; pt[0] = setPoint(0 , 0); pt[1] = setPoint(4 , 0); pt[2] = setPoint(4 , 3); showPoint(pt , 2); printf("dist between point1 and point2 is %.1f ", distPoint(pt[0] , pt[2])); char *filename = "Info.txt"; saveInfo(pt[0], pt[2], filename); return 0; }
补充说明:
代码是按c89写的,这个标准里必须使用
struct pointT pt1
声明,而不能使用
pointT pt
如果必要,自行修改。
(本人用的编译器比较旧)