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结构
}