首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

请大家帮小弟我找找错:一个分数类重载加减乘除运算符的程序,编译没有异常但是会停止运行

2012-09-25 
请大家帮我找找错:一个分数类重载加减乘除运算符的程序,编译没有错误但是会停止运行。#includeiostreamus

请大家帮我找找错:一个分数类重载加减乘除运算符的程序,编译没有错误但是会停止运行。
#include<iostream>
using namespace std;
class Fenshu

{
public:
Fenshu(){}
Fenshu(int,int);
int getfenzi(){return fenzi;}
int getfenmu(){return fenmu;}
int gcd();
Fenshu operator+(Fenshu c);
Fenshu operator-(Fenshu c);
Fenshu operator*(Fenshu c);
Fenshu operator/(Fenshu c);
void display(){cout<<fenzi<<"/"<<fenmu<<endl;}
private:
int fenzi,fenmu;
};
Fenshu::Fenshu(int myfenzi,int myfenmu)
{
fenzi=myfenzi;
fenmu=myfenmu;
}
int Fenshu::gcd()
{
int temp,g;
if(fenmu!=0)

temp=fenzi/fenmu;
fenzi=fenmu;
fenmu=fenzi%fenmu;
g=fenmu;
return g;
 

}
Fenshu Fenshu::operator +(Fenshu c)
{
Fenshu temp;
temp.fenzi=fenzi*c.fenmu+c.fenzi*fenmu;
temp.fenmu=fenmu*c.fenmu;
temp.fenzi=temp.fenzi/(temp.gcd());
temp.fenmu=temp.fenmu/(temp.gcd());
return temp;
}
Fenshu Fenshu::operator-(Fenshu c)
{
Fenshu temp;
temp.fenzi=c.fenzi*fenmu-c.fenmu*fenzi;
temp.fenmu=c.fenmu*fenmu;
  temp.fenzi=temp.fenzi/(temp.gcd());
temp.fenmu=temp.fenmu/(temp.gcd());
return temp;

}
Fenshu Fenshu::operator *(Fenshu c)
{
Fenshu temp;
temp.fenzi=fenzi*c.fenzi;
temp.fenmu=fenmu*c.fenmu;
  temp.fenzi=temp.fenzi/(temp.gcd());
temp.fenmu=temp.fenmu/(temp.gcd());
return temp;
}
Fenshu Fenshu::operator /(Fenshu c)
{
Fenshu temp;
if(temp.fenmu!=0&&c.fenmu!=0)
temp.fenzi=fenzi*c.fenmu;
temp.fenmu=fenmu*c.fenzi;
temp.fenzi=temp.fenzi/(temp.gcd());
temp.fenmu=temp.fenmu/(temp.gcd());
return temp;
 
 
}
int main()
{
Fenshu c1(8,20),c2(2,4);
Fenshu c;
cout<<"c1=";
c1.display();
cout<<"c2=";
c2.display();
c=c1+c2;
cout<<"c1+c2=";
c.display();
c=c1-c2;

  cout<<"c1=";
c1.display();
cout<<"c2=";
c2.display();
c=c1-c2;
cout<<"c1-c2=";
c.display();
return 0;
}

[解决办法]
楼主是忘记怎么求最大公约数了么??gcd函数写错了!居然能够返回值为0.然后让一个数据除以0.导致出错了

热点排行
Bad Request.