用类求两点间的距离
設計一個用來表示直角坐標系的Location類,在主程序中創建類Location的兩個對象A和B,要求A的坐標點在第3象限,B的坐標點在第2象限,分別采用成員函數和友元函數計算給定兩個坐標點之間的距離,要求按如下格式輸出結果:
A(x1,y1), B(x2,y2),
Distance1=d1
Distance2=d2
其中:x1、y1、x2、y2為指定坐標值,d1和d2為兩個坐標點之間的距離。
#include<iostream> #include<cmath> using namespace std; class Location {public:Location(double a,double b);//構造函數; double getx();double gety();double distance(Location &d);//成員函數 friend double distance1(Location &,Location &);//友元函數; private:double x,y; }; Location::Location(double a,double b)//構造函數定義; {x=a;y=b; } double Location:: getx() {return x; } double Location::gety() {return y; } double Location::distance(Location &d) {double d1;d1=sqrt((this->x-d.x)*(this->x-d.x)+(this->y-d.y)*(this->y-d.y));cout<<"Distance1="<<d1<<endl;return 0; } double distance1(Location &a,Location &b) {double d2;d2=sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));cout<<"Distance2="<<d2<<endl;return 0; } int main() {Location A(-1,-1);Location B(-1,1);cout<<"A("<<A.getx()<<","<<A.gety()<<endl;A.distance(B);distance(A,B);return 0; }總結
- 上一篇: 8086中断系统——《x86汇编语言:从
- 下一篇: java中1和1.0_在Java中如何以