比率类中的运算符/=以错误的方式工作

Operator/= in Ratio Class is working in a wrong way

本文关键字:错误 方式 工作 运算符 比率      更新时间:2023-10-16

请看这段代码:

#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();
}

执行此代码后,(y)应该是5/4,我已经用手计算了好几遍!但是在打印后的输出 (y) 中,它显示 4/5!它被它颠倒了不应该!

我的代码问题在哪里? 真的我已经检查了好几次,似乎没有任何问题!这是一个家庭作业:)

你是如何决定它应该是 5/4 的?(2/5)/(1/2) = 4/5,这是正确的结果。也许您正在计算 x/=y 而不是当您期望 5/4 时。

y/=xy = y/x 相同,后者2/5 / 1/2 2/5 x 2/1 = 4/5