第七周任务2

/* (程序头部注释开始)
* 程序的版权和版本声明部分
* Copyright (c) 2012, 烟台大学计算机学院学生 
* All rights reserved.
* 文件名称: 求点类中距离
* 作 者:     于晨
* 完成日期: 2012 年 04月 01 日
* 版 本 号: 1.045
* 对任务及求解方法的描述部分
* 输入描述:两个坐标点
* 问题描述: 如何用友元访问,比较一般函数之间的区别
* 程序输出: 点间距
* 程序头部的注释结束
*/
[cpp]  view plain copy
  1. #include<iostream>     
  2.   
  3. #include<cmath>     
  4.   
  5. using namespace std;    
  6.   
  7. class CPoint    
  8. {    
  9. private:    
  10.     double x;      // 横坐标     
  11.     double y;     // 纵坐标     
  12. public:    
  13.     CPoint(double xx=0, double yy=0):x(xx), y(yy){}    
  14.     double Distance1(CPoint p) const;       // 两点之间的距离(一点是当前点,另一点为参数p)    
  15.     friend double Distance2(CPoint &,CPoint &);  //友元函数实现求两点距离  
  16.     void input();        //以x,y 形式输入坐标点     
  17.     void output();      //以(x,y) 形式输出坐标点    
  18.     double getx(){return x;}      //用于得到x  
  19.     double gety(){return y;}   //用于得到y  
  20. };  
  21.   
  22. double Distance3(CPoint &,CPoint &);  
  23.   
  24. double CPoint::Distance1(CPoint p) const    
  25. {    
  26.     return sqrt((p.x - x) * (p.x - x) + (p.y - y) * (p.y - y));    
  27. }    
  28.   
  29. void CPoint::input()    
  30. {    
  31.     char c;    
  32.   
  33.     cout << "请输入点坐标:(格式:x,y)" << endl;    
  34.   
  35.     do    
  36.     {    
  37.         cin >> x >> c >> y;    
  38.   
  39.         if(c == ',')    
  40.         {    
  41.             break;    
  42.         }    
  43.   
  44.         cout << "格式不正确,请重新输入:" << endl;    
  45.   
  46.     }while(1);    
  47. }    
  48.   
  49. void CPoint::output()    
  50. {    
  51.     cout << "点坐标(" << x << "," << y << ")" << endl;    
  52. }    
  53.   
  54. double Distance2(CPoint &p1,CPoint &p2)  
  55. {  
  56.     return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));  
  57. }  
  58.   
  59. double Distance3(CPoint &p1,CPoint &p2)  
  60. {  
  61.     return sqrt((p1.getx() - p2.getx()) * (p1.getx() - p2.getx()) + (p1.gety() - p2.gety()) * (p1.gety() - p2.gety()));  
  62. }  
  63.   
  64. int main()    
  65. {    
  66.     CPoint c1, c2;    
  67.   
  68.     c1.input();    
  69.   
  70.     c2.input();    
  71.   
  72.     c1.output();    
  73.   
  74.     c2.output();    
  75.   
  76.     cout << "两点间的距离是:" << c1.Distance1(c2) << endl;   
  77.   
  78.     cout << "两点间的距离是:" << Distance2(c1, c2) << endl;  
  79.   
  80.     cout << "两点间的距离是:" << Distance3(c1, c2) << endl;  
  81.   
  82.     system("pause");    
  83. }    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值