算术运算打印错误的结果

时间:2015-11-06 10:41:19

标签: c++

我制作了一个简单的程序,通过算术运算来打印数字。除了最后一个操作员,每件事都很好。它打印结果为:1这是错误的,预期结果应为1.7。 我的计划有什么问题。为什么这样打印?

#include <iostream>
#include <exception>


class Money
{
public:
    Money(float amount = 0) : m_amount(amount){}

    // logic operations
    bool operator==(const Money& other) const
    {
        return m_amount == other.m_amount;
    }

    // arithmetic operations
    Money operator*=(const Money& other)
    {
        m_amount *= other.m_amount;
        return *this;
    }

    Money operator/=(const Money& other)
    {
        if (other.m_amount == 0)
            throw std::invalid_argument("Division by zero");

        m_amount /= other.m_amount;
        return *this;
    }

    friend std::ostream& operator<<(std::ostream& os, const Money& money)
    {
        return os << '$' << money.m_amount;
    }

private:
    float m_amount;
};

int main()
{
    Money my_money(1.7f);

    std::cout << (my_money *= my_money) << '\n';
    std::cout << (my_money /= my_money) << '\n'; // <-- wrong it should be 1.7
}

1 个答案:

答案 0 :(得分:2)

my_money /= my_money

在数学谈话中

x = a/a, x,a ∈ ℝ\{0}

因为(ℝ,+,⋅)构成一个字段,必须产生乘法子组的一个元素(ℝ,⋅),即为1.