请看这个代码:
#include <iostream>
using namespace std;
class Ratio
{
public:
Ratio(int a=0, int b=1) : num(a), den(b) {}
Ratio& operator/=(const Ratio&);
void print() {cout << num << "/" << den << endl;}
private:
int num, den;
};
Ratio& Ratio::operator/=(const Ratio& r)
{
num*=r.den;
den*=r.num;
return *this;
}
int main()
{
Ratio x(1,2), y(2,5);
y/=x;
y.print();
}
Run Code Online (Sandbox Code Playgroud)
执行此代码后,(y)应为5/4,我用手计算了好几次!但是在打印后的输出(y)中显示为4/5!它倒是不应该!
我的代码在哪里出问题?我真的已经多次检查了几次,看来它没有任何问题!这是一个功课:)
| 归档时间: |
|
| 查看次数: |
350 次 |
| 最近记录: |