标签:
上大一,老师布置了一道题,内容就是:两个有理数相加(要求输入时以分数形式,输出时也以分数形式),这道题用了大概2个多小时吧(欢迎指导),废话不多说了,直接上程序:
#include<iostream>
using namespace std;
class rational
{
public:
void setnumber(int n,int d);
void getnumber(int& n,int& d);
void gcd(int n,int d);
bool operator==(int)const;
rational operator+(const rational& r) const;
rational operator-(const rational& r) const;
rational operator*(const rational& r) const;
rational operator/(const rational& r) const;
private:
int numerator;
int denominator;
};
void rational::setnumber(int n,int d)
{
numerator=n;denominator=d;
}
void rational::getnumber(int& n,int& d)
{
n=numerator;d=denominator;
}
void rational::gcd(int n,int d)
{
int a,b,c;
a=n;b=d;
if(n>d)
{
do
{
c=a%b;
a=b;
b=c;
}while(c=0);
numerator=n/a;
denominator=d/a;
}
else
{
do
{
c=b%a;
b=a;
a=c;
}while(c=0);
numerator=n/b;
denominator=d/b;
}
}
istream& operator>>(istream& is,rational& r)
{
int n,d;
is>>n;
is.ignore(1);
is>>d;
r.setnumber(n,d);
return is;
}
ostream& operator<<(ostream& os,rational& r)
{
int n,d;
r.getnumber(n,d);
os<<n<<"/"<<d;
return os;
}
bool rational::operator==(int)const
{
if(denominator==0)
return true;
else
return false;
}
rational rational::operator+(const rational& r) const
{
rational temp;
temp.numerator=numerator*r.denominator+r.numerator*denominator;
temp.denominator=denominator*r.denominator;
return temp;
}
rational rational::operator-(const rational& r) const
{
rational temp;
temp.numerator=numerator*r.denominator-r.numerator*denominator;
temp.denominator=denominator*r.denominator;
return temp;
}
rational rational::operator*(const rational& r) const
{
rational temp;
temp.numerator=numerator*r.numerator;
temp.denominator=denominator*r.denominator;
return temp;
}
rational rational::operator/(const rational& r) const
{
rational temp;
temp.numerator=numerator*r.denominator;
temp.denominator=denominator*r.numerator;
return temp;
}
void main()
{
int n,d;
char ch;
rational r1;
rational r2;
rational r3;
cin>>r1;
cin>>ch;
cin>>r2;
if(r1==0||r2==0)
{
cout<<"error"<<endl;
}
else
{
switch(ch)
{
case‘+‘:
r3=r1+r2;
break;
case‘-‘:
r3=r1-r2;
break;
case‘*‘:
r3=r1*r2;
break;
case‘/‘:
r3=r1/r2;
break;
default:
cout<<"wrong";
}
r3.getnumber(n,d);
r3.gcd(n,d);
r3.getnumber(n,d);
cout<<r3<<endl;
}
}
由于对博客不熟悉,不会发图片,就这样子了,看不懂的可以提问题。
标签:
原文地址:http://www.cnblogs.com/1521299249study/p/4401091.html