我相信我已经纠正了大部分计划。到目前为止它没有错误,但我在执行的某个部分期间收到奇数值:
我的输出是:
0/2 3/4 Cannot divide by zero Cannot divide by zero 0 0 Cannot divide by zero ____________________________________
我知道我在函数中的计算是正确的,但我相信它们没有收到传递给它们的变量的保存值。
这是我的班级:
#include <iostream>
#include <string.h>
#include <fstream>
using namespace std;
class fraction {
private:
long num, den;
public:
fraction() {}
fraction(int n, int d) {
num = n;
if (d == 0) {
cout << "Careful there, Tim..." << endl;
exit(0);
} else
den = d;
}
void setNum(long l_num) { num = l_num; }
void setDen(long l_den) { den = l_den; }
long getNum() { return num; }
long getDen() { return den; }
long add(fraction& a, fraction& b) {
int n = (a.getNum() * b.getDen()) + (b.getNum() * a.getDen());
int d = a.getNum() * b.getDen();
num = n / gcd(n, d);
den = d / gcd(n, d);
return num;
return den;
}
long sub(fraction& a, fraction& b) {
int n = a.getNum() * b.getDen() - b.getNum() * a.getDen();
int d = a.getNum() * b.getDen();
num = n / gcd(n, d);
den = d / gcd(n, d);
}
long mult(fraction& a, fraction& b) {
int n = a.getNum() * b.getNum();
int d = a.getDen() * b.getDen();
num = n / gcd(n, d);
den = d / gcd(n, d);
}
long div(fraction& a, fraction& b) {
int n = a.getNum() * b.getDen();
int d = a.getDen() * b.getNum();
num = n / gcd(n, d);
den = d / gcd(n, d);
}
long inc(fraction& a) {
int n = a.getNum() + 1;
int d = a.getDen() + 1;
}
long gcd(long n, long d) {
int remainder;
while (d != 0) {
remainder = n % d;
n = d;
d = remainder;
}
return n;
}
void print() // Display method
{
if (den == 1)
cout << num << endl;
else if (den == 0)
cout << "Cannot divide by zero" << endl;
else
cout << num << "/" << den << endl;
}
};
我的导师给了我们严格的指示,不要修改他给定的int main()
,但现在是:
int main() { // define seven instances of the class fraction
fraction f1, f2, f3, f4, f5, f6, f7;
// set values for the numerator and denominator to f1 and print
// them
f1.setDen(2L);
f1.setNum(0L);
f1.print();
// set values for the numerator and denominator to f2 and print them
f2.setDen(4L);
f2.setNum(3L);
f2.print();
f3.add(f1, f2);
f3.print();
f4.sub(f1, f2);
f4.print();
f5.mult(f1, f2);
f5.print();
f6.div(f1, f2);
f6.print();
f7.inc(f1);
f7.print();
}
我之前已经从SO请求了这个程序的帮助,并且我和非常好的人接触过。我已经两次给我的教授发了一封电子邮件,并打电话给他的办公室。他没有回答//在开放上阅读我的电子邮件读取cc <还没有回复我留下的语音邮件。
答案 0 :(得分:2)
我认为你在计算d时使用add / sub函数找到了问题,
int d = a.getNum() * b.getDen();
你弄错了,对于D,你应该这样做:
int d = a.getDen() * b.getDen();
从你的添加功能你应该删除两个回报
long add(fraction& a, fraction& b) {
int n = (a.getNum() * b.getDen()) + (b.getNum() * a.getDen());
int d = a.getNum() * b.getDen();
num = n / gcd(n, d);
den = d / gcd(n, d);
//return num;
//return den;
}
在您的inc函数上,您忘记设置num,den:
long inc(fraction& a) {
num = a.getNum() + 1;
den = a.getDen() + 1;
}
检查http://ideone.com/C7KgD3以查看结果