结构体实现两点之间距离和中点的计算

#include<stdio.h>
#include<math.h>
struct point//定义结构体
{
	double x;
	double y;
};
double dis(struct point a,struct point b)//两点之间的距离
{
	double c;
	c=pow(a.x-b.x,2)+pow(a.y-b.y,2);
	return sqrt(c);
 } 
struct point mid_point(struct point a,struct point b)//两点的中点,返回的是一个点,所以要用struct point定义
 {
 	struct point p_m;
 	p_m.x=(a.x+b.x)/2;
 	p_m.y=(a.y+b.y)/2;
 	return p_m;
 }
main()
{
	struct point p1={0,0};
	struct point p2={3,4};
	struct point p_m;
	printf("两点间的距离是%lf\n",dis(p1,p2));
	p_m=mid_point(p1,p2);
	printf("中点为(%lf,%lf)\n",p_m.x,p_m.y);
}
double dis(struct point a,struct point b)
struct point mid_point(struct point a,struct point b)
//要注意这两条不可以写*a和*b

否则会报错说:point不能转换成point*传入函数中

c=pow(a.x-b.x,2)+pow(a.y-b.y,2);

再注意一下pow函数需要两个参数pow(x,n),x是拿来算的数,n是x的幂次方,例如pow(2,4)意为2的四次方。

我今天算是第一次感受到了结构体的香

struct point mid_point(struct point a,struct point b)
 {
 	struct point p_m;
 	p_m.x=(a.x+b.x)/2;
 	p_m.y=(a.y+b.y)/2;
 	return p_m;
 }

就是它了,要注意return返回的值要和函数被定义的类型相同,比如这里就不可以用int mid_point了,因为返回值的类型是struct point,所以函数类型也得用struct point定义。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值