题目描述
完成一维点类Point、二维平面点类Point_2D、三维空间点类Point_3D的类定义的程序填空。
并根据主函数要求完成每个点到原点的距离结果输出。
假设所有点坐标都是整数,输出的距离结果要求精确到小数点后2位。
类声明
#include"iostream"
#include<iomanip>
#include<cmath>
using namespace std;
class Point
{
protected:
int x;
public:
Point(int);
void distance();
};
class Point_2D:public Point
{
protected:
int y;
public:
Point_2D(int,int);
void distance();
};
class Point_3D:public Point_2D
{
protected:
int z;
public:
Point_3D(int,int,int);
void distance();
};
主函数
int main()
{
int num,tx,ty,tz;
cin>>num;
while(num)
{
switch(num)
{
case 1:
{
cin>>tx;
Point p1(tx);
p1.distance();
break;
}
case 2:
{
cin>>tx>>ty;
Point_2D p2(tx,ty);
p2.distance();
break;
}
case 3:
{
cin>>tx>>ty>>tz;
Point_3D p3(tx,ty,tz);
p3.distance();
break;
}
}
cin>>num;
}
}
输入
每行输入一个点的信息,第一个参数表示点的维度,后面参数表示点坐标数值
以输入0结束
输出
输出每个点到原点的距离具体看样例
输入样例1
1 -3
2 2 3
3 3 4 5
0
输出样例1
Distance between [-3] and [0] = 3.00
Distance between [2, 3] and [0, 0] = 3.61
Distance between [3, 4, 5] and [0, 0, 0] = 7.07
思路分析
这道题唯一吸引人的地方就在于只有当你本地跑出理想结果,满怀信心地提交代码却意味看到答案错误的抓狂,你是无论如何都想不到,会有那么多奇奇怪怪不应该存在的空格在输出中,然而,就是少了空格。
AC代码
Point::Point(int x):x(x){}
void Point::distance()
{
float dist=x*x;
cout<<"Distance between ["<<x<<"] and [0] = "<<fixed<<setprecision(2)<<sqrt(dist)<<endl;
}
Point_2D::Point_2D(int x,int y):Point(x),y(y){}
void Point_2D::distance()
{
float dist=x*x+y*y;
cout<<"Distance between ["<<x<<", "<<y<<"] and [0, 0] = "<<fixed<<setprecision(2)<<sqrt(dist)<<endl;
}
Point_3D::Point_3D(int x,int y,int z):Point_2D(x,y),z(z){}
void Point_3D::distance()
{
float dist=x*x+y*y+z*z;
cout<<"Distance between ["<<x<<", "<<y<<", "<<z<<"] and [0, 0, 0] = "<<fixed<<setprecision(2)<<sqrt(dist)<<endl;
}