蓝桥杯练习系统 C++ CH08 01【函数重载】

题目:

问题描述
  已知一个有理数类Zrf_Ratio,实现如下的操作符重载形式:
  friend std::ostream& operator<<(std::ostream&, const zrf_Ratio&);//输出最简分数
  friend std::istream& operator>>(std::istream&, zrf_Ratio&);
  friend bool operator==(const zrf_Ratio&, const zrf_Ratio&);
  friend bool operator<(const zrf_Ratio&, const zrf_Ratio&);
测试
  测试时主程序会输入四个整数a, b, c, d,表示两个分数a/b和c/d。要求输出最简分数以及两个分数相等和大小的比较结果。
样例输入
1 7 26 25
样例输出
zrf is:1/7; ssh is:26/25
(zrf==ssh) is:0; (zrf<ssh) is:1
 
蓝桥杯真的很破 我提交的代码总是编译出错  点进去看评测 居然在我的代码后面附加了以前提交的代码一起编译   无语啊!!!!!!!!!!!!!!总是编译出错 真想发火
 
 1 #include<iostream>
 2 using namespace std;
 3 class zrf_Ratio{
 4     public:
 5         int son,mom;
 6     friend std::ostream& operator<<(std::ostream& zout,const zrf_Ratio& z);//输出最简分数
 7     friend istream &operator>>(istream &zin,zrf_Ratio &z);
 8     friend bool operator==(const zrf_Ratio &a,const zrf_Ratio &b);
 9     friend bool operator<(const zrf_Ratio &a,const zrf_Ratio &b);
10 };
11 ostream& operator<<(ostream &zout,const zrf_Ratio &z){//输出最简分数 
12     int x,y;//求x,y的最大公约数
13     x=z.son;
14     y=z.mom;
15     int tmp;
16     if(x<y){//保证x>y 
17         tmp=x;
18         x=y;
19         y=tmp;
20     }
21     //辗转相除求最大公约数 
22     do{
23         tmp=x%y;
24         x=y;
25         y=tmp;
26     }while(tmp!=0);
27     //得到tmp即为最大公约数
28     zout<<z.son/x<<"/"<<z.mom/x;
29     return zout;
30 }
31 istream& operator>>(istream &zin,zrf_Ratio& z){
32     int x,y;
33     zin>>x>>y;
34     z.son=x;
35     z.mom=y;
36     return zin;
37 }
38 bool operator==(const zrf_Ratio& a, const zrf_Ratio& b){
39     int ax,ay,bx,by;
40     ax=a.son;
41     ay=a.mom;
42     bx=b.son;
43     by=b.mom;
44     return ax*by==bx*ay;
45 }
46 bool operator<(const zrf_Ratio& a, const zrf_Ratio& b){
47     int ax,ay,bx,by;
48     ax=a.son;
49     ay=a.mom;
50     bx=b.son;
51     by=b.mom;
52     return (ax*by-bx*ay)*(ay*by)<0;
53 }
54 int main(){
55     zrf_Ratio ssh,zrf;
56     cin>>zrf>>ssh;
57     cout<<"zrf is:"<<zrf<<"; ssh if:"<<ssh<<endl;
58     cout<<"(zrf==ssh) is:";
59     if(zrf==ssh) cout<<"1 ";
60     else cout<<"0 ";
61     cout<<"(zrf<ssh) is:";
62     if(zrf<ssh) cout<<"1"<<endl;
63     else cout<<"0"<<endl;
64     
65 }

 

 
posted @ 2017-03-11 19:25  Elaine_DWL  阅读(1069)  评论(0编辑  收藏  举报