![]() |
#2
rjsp2016-03-18 09:28
你这是乱用对象,画虎不成反类犬。
我教你一个方法:先别急着设计类和接口,先将怎么使用的用例写好,然后根据用例去完成接口。 也就是先写出 int main( void ) { fra a, b; cin >> a >> b; cout << (a+b) << endl; } 然后根据这段用例去设计 fra 吧。 ![]() //////////////////////////////////////////////////////// #include <iostream> #include <exception> struct fraction { fraction( int n=0, int d=1 ); fraction& reduct( void ); private: int numerator; int denominator; friend std::istream& operator>>( std::istream&, fraction& f ); friend std::ostream& operator<<( std::ostream&, const fraction& f ); friend fraction operator+( const fraction& lhs, const fraction& rhs ); }; //////////////////////////////////////////////////////// fraction::fraction( int n, int d ) : numerator(n), denominator(d) { if( d == 0 ) throw std::invalid_argument("divided by zero"); } fraction& fraction::reduct( void ) { int a = numerator; int b = denominator; while( b != 0 ) { int c = a%b; a = b; b = c; } numerator /= a; denominator /= a; if( denominator < 0 ) { numerator = -numerator; denominator = -denominator; } return *this; } std::istream& operator>>( std::istream& is, fraction& f ) { int n, d; if( is>>n>>d ) f = fraction(n,d); return is; } std::ostream& operator<<( std::ostream& os, const fraction& f ) { return os << f.numerator << '/' << f.denominator; } fraction operator+( const fraction& lhs, const fraction& rhs ) { int n = lhs.numerator*rhs.denominator + rhs.numerator*lhs.denominator; // 严谨一些的话,这里应该判断是否抛出std::overflow_error int d = lhs.denominator*rhs.denominator; return fraction(n,d).reduct(); } //////////////////////////////////////////////////////// using namespace std; int main( void ) { fraction a, b; try { if( !(cin>>a>>b) ) { cerr << "input error.\n"; return 1; } } catch( const std::exception& e ) { cerr << e.what() << '\n'; return 2; } cout << a << " + " << b << " = " << (a+b) << endl; return 0; } 测试用例 输入 a b c d 输出 input error. 输入 3 2 1 0 输出 divided by zero 输入 -30 -42 165 -195 输出 -30/-42 + 165/-195 = -12/91 |
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
class fra{
public:
fra(int s, int m);
int getx(){ return x; }
int gety(){ return y; }
int plus(fra a, fra b);
private:
int x, y;
void reduct(int m, int s);
};
fra::fra(int s, int m){
if (s*m < 0){
x = -abs(s);
y = abs(m);
}
else{
x = s;
y = m;
}
};
void fra::reduct(int m, int s){
int max, min, k, t, m1, s1;
m1 = abs(m); s1 = abs(s);
if (m1 >= s1){
max = m1;
min = s1;
}
else {
max = s1;
min = m1;
}
k = max%min;
if (k == 0)
t = min;
else
while (k){
max = min;
min = k;
t = k;
k = max%min;
}
m = m / t;
s = s / t;
cout << "Answer:" << s << "/" << m << endl;
return;
}
int fra::plus(fra a, fra b){
int m, s;
if (a.gety() == 0 || b.gety() == 0){
cout << "ERROR!" << endl;
return 0;
}
m = a.gety()*b.gety();
s = (a.getx()*b.gety()) + (b.getx()*a.gety());
reduct(m, s);
return 0;
}
int main(){
int p, q,k,l;
cin >> p >> q >> k >> l;
fra a(p,q), b(k,l);
fra plus(a, b);//此处a下边提示错误“没有与参数列表匹配的构造函数"fra::fra"实例,参数类型为:(fra,fra)”
return 0;
}