C++分数类对负数不起作用
我正在尝试创建一个分数类,它可以对分数进行运算,就像我们在小学手工操作一样。它可以很好地处理正数,但我尝试过用负数实现它,我得到了断点错误。如果有人能告诉我它出了什么问题,那就太好了C++分数类对负数不起作用,c++,class,C++,Class,我正在尝试创建一个分数类,它可以对分数进行运算,就像我们在小学手工操作一样。它可以很好地处理正数,但我尝试过用负数实现它,我得到了断点错误。如果有人能告诉我它出了什么问题,那就太好了 #include <iostream> #include <cmath> using namespace std; class fraction { private: long int n; long int d; long int gcd(); public:
#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;
}
该错误是由print是非常量成员函数这一事实引起的 使用时:
(f-g).print();
该函数被称为临时对象,这有利于调用常量成员函数,而不是非常量成员函数
您可以通过以下方式解决此问题:
将打印更改为常量成员函数
通过将f-g分配给对象并在该对象上调用print
fraction res = f-g;
res.print();
我建议使用第一种方法
更新
当n或d为负值时,gcd中存在问题。将其更改为:
long int fraction::gcd()
{
long int divisor = 1;
// Deal with only positive numbers when computing the gcd.
long int tempN = n < 0 ? -n : n;
long int tempD = d < 0 ? -d : d;
for (long int i = 1; (i <= tempN && i <= tempD) ; i++)
{
if ((tempN % i == 0) && (tempD % i == 0))
{
divisor=i;
}
}
return divisor;
}
请发布一个。另外,发布错误消息会很有帮助。调用print时,括号在哪里?我认为这也不是问题。即使我取消了print函数,只调用了表达式f-g;代码仍然不起作用。@shoestringfries,这是一个问题。第二个问题是gcd。请参阅更新的答案。我认为这就是问题所在。谢谢:D