问题及代码:
/*
*Copyright (c)2015,烟台大学计算机与控制工程学院
*All rights reserved.
*文件名称:point.cpp
*作 者:单昕昕
*完成日期:2015年4月4日
*版 本 号:v1.0
*
*问题描述:
设计平面坐标点类,计算两点之间距离、到原点距离、关于坐标轴和原点的对称点等。在设计中,由于求距离、求对称点等操作对原对象不能造成任何改变,所以,将这些函数设计为常成员函数是合适的,能够避免数据成员被无意更改。
*程序输入:点的坐标。
*程序输出:两点之间距离、到原点距离、关于坐标轴和原点的对称点等。
*/
#include <iostream>
#include <cmath>
using namespace std;
class CPoint
{
private:
double x; // 横坐标
double y; // 纵坐标
public:
CPoint(double xx=0,double yy=0);
double Distance1(CPoint p) const; //两点之间的距离(一点是当前点——想到this了吗?,另一点为p)
double Distance0() const; // 到原点(0,0)的距离
CPoint SymmetricAxis(char style) const;//style取'x','y'和'o'分别表示按x轴, y轴, 原点对称
void input(); //以x,y 形式输入坐标点
void output(); //以(x,y) 形式输出坐标点
};
CPoint::CPoint(double xx,double yy)
{
x=xx;
y=yy;
}
double CPoint::Distance1(CPoint p) const//两点之间的距离(一点是当前点——想到this了吗?,另一点为p)
{
return sqrt((p.x-x)*(p.x-x)+((p.y-y)*(p.y-y)));
}
double CPoint::Distance0() const// 到原点(0,0)的距离
{
return (sqrt(x*x+y*y));
}
CPoint CPoint::SymmetricAxis(char style) const//style取'x','y'和'o'分别表示按x轴, y轴, 原点对称
{
CPoint p(this->x,this->y);
switch(style)
{
case'x':
p.y=-y;
break;
case'y':
p.x=-x;
break;
case'o':
p.x=-x;
p.y=-y;
break;
}
return p;
}
void CPoint::input()//以x,y 形式输入坐标点
{
char c;
cin>>this->x>>c>>this->y;
}
void CPoint::output()//以(x,y) 形式输出坐标点
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
int main()
{
CPoint p1,p2,p;
cout<<"请以“x,y”形式输入点p1的坐标:";
p1.input();
cout<<"请以“x,y”形式输入点p2的坐标:";
p2.input();
cout<<"p1到p2的距离="<<p1.Distance1(p2)<<endl;
cout<<"点p1到原点(0,0)的距离="<<p1.Distance0()<<endl;
cout<<"点p2到原点(0,0)的距离="<<p2.Distance0()<<endl;
cout<<"下面对p1点进行变换:"<<endl;
cout<<"p1按x轴对称变换后:";
p=p1.SymmetricAxis('x');
p.output();
cout<<"p1按y轴对称变换后:";
p=p1.SymmetricAxis('y');
p.output();
cout<<"p1按原点对称变换后:";
p=p1.SymmetricAxis('o');
p.output();
cout<<"下面对p2点进行变换:"<<endl;
cout<<"p2按x轴对称变换后:";
p=p2.SymmetricAxis('x');
p.output();
cout<<"p2按y轴对称变换后:";
p=p2.SymmetricAxis('y');
p.output();
cout<<"p2按原点对称变换后:";
p=p2.SymmetricAxis('o');
p.output();
return 0;
}
运行结果:
知识点总结:
平面坐标点类。
常成员函数。
学习心得:
一开始不会使用CPoint CPoint::SymmetricAxis(char style),后来看了注释部分的提示才写出来。