函数和结构<2>

1.另一个处理结构的函数实例

描图片上的某一位置即坐标,需要x偏移量和y偏移量,也就是x坐标和y坐标。构建一个直角坐标系

 sruct rect{   //坐标结构
  double x;
  double y;
};

另一种描述是描述一个点(偏离原点的方向和距离)(东偏北40°,距离和角度形成的极坐标)

sruct polar{
    double distance;
    double angle;
    
};

创建显示polar内容的函数,结构定义的是弧度值要乘以Π/2=57.29577951得角度值

void ShowPolar(polar dapos){
    using namespace std;
    const double Rad=57.29577951;
    cout<<"distance="<<dapos.distance;
    cout<<", angle="<<dapos.angle;
    cout<<"  degresss\n";
    
    
}

编写一个直角坐标转换为极坐标的函数,该函数接受一个rect参数,返回一个polar结构。需要数学库的函数,根据毕达哥拉斯定理,使用水平和垂直坐标系计算距离:

distance = sqrt(x*x+y*y)    //sqrt()计算距离 勾股定理

数学库中atan2()函数可根据x和y的值

angle =atan2(y,x)
polar rect_to_polar(rect xypos){
	polar answer;
	
	answer.distance=
		sqrt(xypos.x*xypos.x+xypos.y*xypos.y);
	answer.angle=
		atan2(xypos.x,xypos.y)
	return answer;    //返回一个polar结构
}

最后代码完善

#include<iostream>
#include<cmath>
using namespace std;
struct rect{   //坐标结构
  double x;
  double y;
};
struct polar {
    double distance;
    double angle;

};
polar rect_to_polar(rect xypos);
void ShowPolar(polar dapos);
int main() {
    rect rplace;
    polar pplace;

    cout << "Enter the x and y values:";
    while (cin >> rplace.x >> rplace.y) {
        pplace = rect_to_polar(rplace);
        ShowPolar(pplace);
        cout << "Next two numbers(q to quit):" << endl;;
    }
    cout << "Done!!";


    return 0;
}
void ShowPolar(polar dapos) {
    using namespace std;
    const double Rad = 57.29577951;
    cout << "distance=" << dapos .distance;
    cout << ", angle=" << dapos .angle;
    cout << "  degresss\n";

}
polar rect_to_polar(rect xypos) {
    polar answer;

    answer.distance =
        sqrt(xypos.x * xypos.x+ xypos.y * xypos.y);
    answer.angle =
        atan2(xypos.x, xypos.y);
        return answer;    //返回一个polar结构
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值