蓝桥杯-算法训练-C++ CH08 01

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_41550842/article/details/78979189
算法训练-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


此题真的是坑到我了,个人觉得题目并没有描述清楚,于是看到题目就直接开写,害得我辛辛苦苦把有理数类全部写了一遍,还
补充了主函数。写完后测试完全正确,结果CE一发,顿时感觉受到了欺骗,感觉被题目坑了一发。看完自己交的代码后焕然大悟
原来它自动已经给出有理数类和主函数,仅仅只要你补充题目要求的四个函数,而且其中的变量名还需和他已给出的代码相同,
不能违背,否则,恭喜你又要CE一发了。下面是AC代码,仅供参考。

int zrf_Gcd(int , int );
ostream& operator<<(ostream &out,const zrf_Ratio &p)
{
	int t=zrf_Gcd(p.num,p.den);
	out<<p.num/t<<'/'<<p.den/t;
	return out;
}
istream& operator >>(istream &in,zrf_Ratio &p)
{
	int a,b;
	in>>a>>b;
	p.num=a; p.den=b;
	return in;
}
bool operator ==(const zrf_Ratio &p, const zrf_Ratio &q)
{
	if(p.num*(1.0)/p.den==q.num*(1.0)/q.den)
		return true;
	return false;
}
bool operator <(const zrf_Ratio &p, const zrf_Ratio &q)
{
	if(p.num*(1.0)/p.den<q.num*(1.0)/q.den)
		return true;
	return false;
}
以下是我第一次交的完整版的代码:


#include <iostream>
using namespace std;
int gcd(int a,int b)
{
	int t;
	if(a<b)
		swap(a,b);
	while(a%b)
	{
		t=a%b;
		a=b;
		b=t;
	}
	return b;
}
class zrf_ratio
{
private:
	int a,b;
public:
	friend ostream& operator <<(ostream& ,const zrf_ratio&);
	friend istream& operator >>(istream& ,zrf_ratio&);
	friend bool operator ==(const zrf_ratio& , const zrf_ratio&);
	friend bool operator <(const zrf_ratio& , const zrf_ratio&);
};
ostream& operator<<(ostream &out,const zrf_ratio &p)
{
	int t=gcd(p.a,p.b);
	out<<p.a/t<<'/'<<p.b/t;
	return out;
}
istream& operator >>(istream &in,zrf_ratio &p)
{
	int a,b;
	in>>a>>b;
	p.a=a; p.b=b;
	return in;
}
bool operator ==(const zrf_ratio &p, const zrf_ratio &q)
{
	if(p.a*(1.0)/p.b==q.a*(1.0)/q.b)
		return true;
	return false;
}
bool operator <(const zrf_ratio &p, const zrf_ratio &q)
{
	if(p.a*(1.0)/p.b<q.a*(1.0)/q.b)
		return true;
	return false;
}
int main()
{
	zrf_ratio zrf,ssh;
	cin>>zrf>>ssh;
	cout<<"zrf is:"<<zrf<<"; "<<"ssh is:"<<ssh<<endl;
	cout<<"(zrf==ssh) is:"<<(zrf==ssh)<<"; "<<"(zrf<ssh) is:"<<(zrf<ssh);
	return 0;
}







猜你喜欢

转载自blog.csdn.net/qq_41550842/article/details/78979189