在默認構造函數里面,分母的默認值不能為0!!
Home | Web Board | ProblemSet | Standing | Status | Statistics |
Problem D: 分數類的模板數組類
Submit: 509 Solved: 350
[ Submit][ Status][ Web Board]
[
Submit][
Status][
Web Board]
Problem D: 分數類的模板數組類
Time Limit: 3 Sec Memory Limit: 128 MBSubmit: 509 Solved: 350
[ Submit][ Status][ Web Board]
Description
封裝一個模板數組類Array,支持一下操作:
1. 構造函數Array(int n),將數組初始化為n個存儲空間;
2. 函數input(int n),讀取最多n個元素,但不能超過數組存儲空間的上限;
3. 重載下標運算符,返回數組的元素。
封裝一個分數類Fract,用來處理分數功能和運算,能支持你的Array類使用。
1. 構造:傳入兩個參數n和m,表示n/m;分數在構造時立即轉化成最簡分數。
2. show()函數:分數輸出為“a/b”或“-a/b”的形式,a、b都是無符號整數。若a為0或b為1,只輸出符號和分子,不輸出“/”和分母。
3. 在分數類上重載+=運算符,進行分數的加法運算。
-----------------------------------------------------------------------------
你設計兩個類:Array類和Fract類,使得main()函數能夠運行並得到正確的輸出。調用格式見append.cc
Input
輸入為兩部分,分別是一組實數測試樣例和一組復數測試樣例。
這兩組測試樣例都以正整數n,且n小於1000,n表示需要輸入n個實數(或分數)。
測試樣例的第二行開始為n個實數(或分數)。其中每個分數輸入為兩個整數n、m,表示分數n/m。
Output
第一部分輸出一個實數,是第一組測試樣例之和;第二部分輸出一個分數,是第二組測試樣例之和。
分數輸出時為最簡形式,負號只會出現在最前面,若分母為1或分子為0,則只輸出一個整數,即分子部分,而沒有“/”和分母部分。
Sample Input
4 6 8 7 5 9 1 3 20 -15 80 150 -9 1 6 6 12 16 -33 -48 6 11 0 -10
Sample Output
26 -17117/2640
HINT
Append Code
#include<iostream> #include<vector> #include<typeinfo> using namespace std; template<typename T> class Array { public: vector<T> a; Array(int n) {} void input(int n) { for(int i=0; i<n; i++) { T tmp; cin>>tmp; a.push_back(tmp); } } T& operator[](int n) { return a[n]; } }; int cccc(int a,int b) { if(!b) return a; return cccc(b,a%b); } class Fract{ public: int n,m; Fract(int a=0,int b=1):n(a),m(b) { int Max,Min,c,x,y; if(a<0) a*=-1; if(b<0) b*=-1; c=cccc(max(a,b),min(a,b)); if(m<0) { n*=-1; m*=-1; } if(c!=1) { n/=c; m/=c; } } void show() { if(n==0||m==1) cout<<n<<endl; else { cout<<n<<"/"<<m<<endl; } } Fract &operator +=(Fract &x){ Fract y(x.n*m+x.m*n,x.m*m); return *this=y; } operator double() { return (double)n/m*1.0; } friend istream &operator>>(istream &is,Fract &f) { is>>f.n>>f.m; return is; } }; Fract operator *(Fract f1,Fract f2) { Fract f(f1.n*f2.n,f1.m*f2.m); return f; } int main() { int n; cin >> n; Array<double> db(1000); db.input(n); double dbsum(0.0); for(int i = 0; i < n; i++) dbsum += db[i]; cout << dbsum << endl; cin >> n; Array<Fract> fr(1000); fr.input(n); Fract frsum(0, 1); for(int i = 0; i < n; i++) frsum += fr[i]; frsum.show(); }