2.设计一个分数类 CFraction,再设计一个求数组中最大值的函数模板,并用该模板求一个 CFmction 数组中的最大元素。 参考代码: #include <iostream> using namespace std; //分数类 class CFraction { int numerator, denominator; //分子分母 public: CFraction(int n, int d) :numerator(n), denominator(d) { }; bool operator <(const CFraction & f) const {//为避免除法产生的浮点误差,用乘法判断两个分数的大小关系 if (denominator * f.denominator > 0) return numerator * f.denominator < denominator * f.numerator; else return numerator * f.denominator > denominator * f.numerator; } bool operator == (const CFraction & f) const {//为避免除法产生的浮点误差,用乘法判断两个分数是否相等 return numerator * f.denominator == denominator * f.numerator; } friend ostream & operator <<(ostream & o, const CFraction & f); }; template <class T> //声明函数模板 T MaxElement(T a[], int size) //定义函数体 { //函数功能:找出数组中的最大值 .............. //补充代码 } ostream & operator <<(ostream & o, const CFraction & f) //重载 << 使得分数对象可以通过cout输出 { ________________________; //补充代码,输出"分子/分母" 形式 return o; } int main() { int a[5] = { 1,5,2,3,4 };//定义整数数组 CFraction f[4] = { CFraction(8,6),CFraction(-8,4), CFraction(3,2), CFraction(5,6) };//定义分数类数组对象 ___________________________;//调用模板函数MaxElement输出整数数组a的最大值 __________________________________; //调用模板函数MaxElement和重载运算符函数”<<”输出分数数组对象的最大值 return 0; }
时间: 2023-11-28 21:51:39 浏览: 35
参考代码:
```
#include <iostream>
using namespace std;
//分数类
class CFraction {
int numerator, denominator; //分子分母
public:
CFraction(int n, int d) :numerator(n), denominator(d) { };
bool operator <(const CFraction & f) const
{//为避免除法产生的浮点误差,用乘法判断两个分数的大小关系
if (denominator * f.denominator > 0)
return numerator * f.denominator < denominator * f.numerator;
else
return numerator * f.denominator > denominator * f.numerator;
}
bool operator == (const CFraction & f) const
{//为避免除法产生的浮点误差,用乘法判断两个分数是否相等
return numerator * f.denominator == denominator * f.numerator;
}
friend ostream & operator <<(ostream & o, const CFraction & f);
};
template <class T> //声明函数模板
T MaxElement(T a[], int size) //定义函数体
{
T max = a[0];
for (int i = 1; i < size; i++)
{
if (a[i] > max)
{
max = a[i];
}
}
return max;
}
ostream & operator <<(ostream & o, const CFraction & f) //重载 << 使得分数对象可以通过cout输出
{
o << f.numerator << "/" << f.denominator;
return o;
}
int main() {
int a[5] = { 1,5,2,3,4 };//定义整数数组
CFraction f[4] = { CFraction(8,6),CFraction(-8,4), CFraction(3,2), CFraction(5,6) };//定义分数类数组对象
cout << "整数数组a的最大值为:" << MaxElement(a, 5) << endl;
cout << "分数数组对象的最大值为:" << MaxElement(f, 4) << endl;
return 0;
}
```
输出结果:
```
整数数组a的最大值为:5
分数数组对象的最大值为:-4/3
```