二、程序填空题。在程序中序号所标志的位置补充代码,使程序能够满足功能说明的要求。将补充的代码填在回答区域所对应的序号处,然后截取运行截图。 下面代码实现分数的程序。 #pragma once #include <iostream> #include <stdio.h> using namespace std; int gcd(int a,int b); //求公约数函数 class fraction { int top; //分子 int bottom; //分母 public: fraction() { top = 0; bottom = 1; } //默认构造函数 fraction(int t,int b){top=t;bottom=b;} //一般构造函数 ( )//① 分数的加法 { top = top * f.bottom + bottom * f.top; bottom = bottom * f.bottom; int a = gcd(top, bottom); top = top / a; bottom = bottom / a; return *this; } int get_top() { ( ) //② 读取分子的值 } int get_bottom(){return bottom;} void set_top(int t){top=t;} void set_bottom(int b){bottom=b;} // 友元函数、分数减法 friend fraction operator-(const fraction& f1,const fraction& f2); friend ostream& operator<<(ostream& ostr,const fraction& cs); //输出 }; fraction operator-(const fraction& f1,const fraction& f2) { fraction f3; f3.top=f1.top*f2.bottom-f1.bottom*f2.top; f3.bottom=f1.bottom*f2.bottom; int a=gcd(f3.top,f3.bottom); f3.top=f3.top/a; f3.bottom=f3.bottom/a; ( ) //③ 返回计算结果 } ostream& operator<<(ostream& ostr,const fraction& cs) { ostr<<cs.top<<"/"<<cs.bottom; return ostr; } ( ) //④一般函数实现乘法,形参为f1,f2 { fraction f3; f3.set_top(f1.get_top()*f2.get_top()); f3.set_bottom(f1.get_bottom()*f2.get_bottom()); int a=gcd(f3.get_top(),f3.get_bottom()); f3.set_top(f3.get_top()/a); f3.set_bottom(f3.get_bottom()/a); return f3; } int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } //main.cpp #include "fraction.h" int main() { fraction f1(1,3); fraction f2(1,6); fraction f3; f3=f1+f2; cout<<f3<<endl; fraction f4(1,2); f3=f4-f2; cout<<f3<<endl; f3=f4*f2; cout<<f3<<endl; }
时间: 2024-03-30 11:40:53 浏览: 63
①
fraction operator+(const fraction& f){
fraction res;
res.top = top * f.bottom + bottom * f.top;
res.bottom = bottom * f.bottom;
int a = gcd(res.top, res.bottom);
res.top = res.top / a;
res.bottom = res.bottom / a;
return res;
}
②
int get_top() const {
return top;
}
③
return f3;
④
fraction operator*(const fraction& f1,const fraction& f2){
fraction f3;
f3.set_top(f1.get_top()*f2.get_top());
f3.set_bottom(f1.get_bottom()*f2.get_bottom());
int a=gcd(f3.get_top(),f3.get_bottom());
f3.set_top(f3.get_top()/a);
f3.set_bottom(f3.get_bottom()/a);
return f3;
}
阅读全文