我正在尝试创建一个可以对分数进行操作的分数类,就像我们在小学时手工操作一样。它与正数一起正常工作,但我尝试用负数实现它,我得到断点错误。如果有人能告诉我它有什么问题,那就太好了。
#include <iostream>
#include <cmath>
using namespace std;
class fraction
{
private:
long int n;
long int d;
long int gcd();
public:
fraction(long int, long int);
long int num(); //returns num
long int denom(); //returns denom
void print(); //print fraction
void reduce(); //reduce fraction to lowest terms
friend double convert(fraction); //convert function to double
friend fraction operator+ (fraction, fraction);//add two fractions, answer in reduced form
friend fraction operator- (fraction, fraction);//subtract two fractions, reduced
};
long int fraction::gcd()
{
long int divisor = 0;
for (long int i = 1; (i <= n && i <= d) ; i++)
{
if ((n % i == 0) && (d % i == 0))
{
divisor=i;
}
}
return divisor;
}
fraction::fraction(long int x, long int y) //constructor
{
n=x;
d=y;
if ((x <= 0) && (y <= 0))
{
n = -x;
d = -y;
}
}
void fraction::reduce() //change value of n and d
{
long int num = n/gcd();
long int denom = d/gcd();
n = num;
d = denom;
}
long int fraction::num()
{
return n;
}
long int fraction::denom()
{
return d;
}
void fraction::print()
{
cout << n << "/" << d;
}
fraction operator- (fraction x, fraction y)
{
x.reduce();
y.reduce();
fraction temp;
temp.n = (x.n)*(y.d) - y.n*(x.d);
temp.d = (x.d)*(y.d);
temp.reduce();
return temp;
}
int main()
{
fraction f(-5,100), g(-1,-2);
(f-g).print; //returns error!
return 0;
}