实验四更改

实验四的Fraction类,当时学的不太好,并没有把所有的功能写完整,现在更新一下
题目要求如下

#include<iostream>
#include<iomanip> 
using namespace std;
class Fraction{
	public:
		Fraction ():top(0),bottom(1) {};
		Fraction (int x,int y):top(x),bottom(y) {};
		Fraction (int x):top(x),bottom(1){};
		void add(Fraction p);
		void sub(Fraction p);
		void mul(Fraction p);
		void div(Fraction p);
		void display()
        {
            cout<<top<<"/"<<bottom<<endl; 
        };  
        void comp(Fraction p);
        int gcd(int a,int b);
        void simplify();
		private:
			int top,bottom;
};
void Fraction::add(Fraction p)
{
	 top=top*p.bottom+p.top*bottom;
    bottom=bottom*p.bottom;
   
}
void Fraction::sub(Fraction p)
{
top=top*p.bottom-p.top*bottom;
    bottom=bottom*p.bottom;
     
    
}
void Fraction::mul(Fraction p)
{
    top=top*p.top;
    bottom=bottom*p.bottom;
   
    
}
void Fraction::div(Fraction p)
{
    top=top*p.bottom;
    bottom=p.top*bottom;
    
    
}
void Fraction::comp(Fraction p)
{
	if(bottom==p.bottom)
	{
		if(top<p.top)
		cout<<"小于"<<endl;
		if(top>p.top)
		cout<<"大于"<<endl;
		if(top==p.top)
		cout<<"等于"<<endl;
	}
	else
	{

	top=top*p.bottom;
	p.top=p.top*bottom;
	if(top<p.top)
	cout<<"小于"<<endl;
		if(top>p.top)
		cout<<"大于"<<endl;
		if(top==p.top)
		cout<<"等于"<<endl;	
}
}
int Fraction::gcd(int a,int b)
{
	int r;
    do{
		r=a%b;
		a=b;
		b=r;
		
	} while(r!=0);
return a;
}
void Fraction::simplify()
{
    if(bottom<0)
    {
        top=-top;
        bottom=-bottom;
    }
    int g=gcd(abs(top),abs(bottom));
    top=top/g;
    bottom=bottom/g;
}
int main()
{
	Fraction a;
Fraction b(3,4);
Fraction c(5);
a.display();
b.display();
c.display();
b.add(c);
b.display();
b.sub(c);
b.display();
b.mul(c);
b.display();
b.div(c);
b.display();
a.comp(b);
system("pause");
int top,bottom;
cout<<"请输入分子"<<endl;
cin>>top;
cout<<"请输入分母"<<endl;
cin>>bottom;
cout<<setw(3)<<top<<endl;
cout<<setw(3)<<"-"<<endl;
cout<<setw(3)<<bottom<<endl;
cout<<"分数3/-4经规范化处理后"<<endl;
Fraction d(3,-4);
d.simplify();
d.display();
cout<<"分数15/21经规范化处理后"<<endl;
Fraction e(15,21);
e.simplify();
e.display();
cout<<"分数-2/-6经规范化处理后"<<endl;
Fraction f(-2,-6);
f.simplify();
f.display(); 
return 0;
}

肯定还会有一些错误,还请大佬指教

posted @ 2018-06-17 21:49  雪卿狂  阅读(146)  评论(0编辑  收藏  举报