C语言习题(结构)

实际应用中经常会用到二维平面上的点,点的操作包括设置点的位置( 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)\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[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\n", distPoint(pt[0] , pt[2]));
    
    char *filename = "Info.txt";
    saveInfo(pt[0], pt[2], filename);
    
    return 0;
}

 补充说明:

代码是按c89写的,这个标准里必须使用

struct pointT pt1

声明,而不能使用

pointT pt

如果必要,自行修改。

 

(本人用的编译器比较旧)

 

转载于:https://www.cnblogs.com/xkxf/p/6227220.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值