数学运算后输出不正确

问题描述 投票:0回答:1

目前,我正在研究 Bjarne Stroustrop 的 PPPUC 第二版,但遇到了问题。我的问题是,我的变量在通过数学运算运行后无法正确输出(我已经为我的班级重载了这些变量)。提示是创建一个 Money 类,用于使用美元和美分进行计算,其中需要遵守美分的 4/5 舍入规则并使用 long int 进行计算,同时还使用美分形式(10000 vs 10.00)进行计算.

这是我的代码:

#include "../std_lib_facilities.h"

constexpr char currency = '$';

long int out_round(double r)
{
    return (r < 0.0) ? (r + 0.5) : (r - 0.5);
}

class Money
{
public:
    class Division_by_zero { }; // custom exception
    // Constructors
    Money() : monetary(0) {}
    Money(long int dollars, long int cents = 0) : monetary(dollars * 100 + cents) {}
    Money(double amount) : monetary(static_cast<long int>(amount * 100)) {}

    // Operators
    Money operator+(const Money& other) const;
    Money operator-(const Money& other) const;
    Money operator*(const Money& other) const;
    Money operator/(const Money& other) const;
    friend std::ostream& operator<<(std::ostream& os, const Money& money);

     
    long int amount() const { return monetary; };
    long int dollars() const { return monetary / 100; };
    long int cents() const { return monetary % 100; };
private:
    long int monetary; 
};

 // Operator definitions
Money Money::operator+(const Money& other) const
{
    return Money(monetary + other.monetary);
}

Money Money::operator-(const Money& other) const
{
    return Money(monetary - other.monetary);
}

Money Money::operator*(const Money& other) const
{
    double result = static_cast<double>(monetary) * other.monetary / 100.0;
    return Money(result); // Return as money type
}

Money Money::operator/(const Money& other) const
{
    if (other.monetary == 0)
    {
        throw std::invalid_argument("Division by zero");
    }
    double result = static_cast<double>(monetary) / other.monetary;
    return Money(result); // Return as money type
}

// Implement the output operator
std::ostream& operator<<(std::ostream& os, const Money& money)
{
    os << money.dollars() << "." << money.cents();
    return os;
}

int main()
{
    Money m1(123, 45); // $123.45
    Money m2(100, 50); // $100.50

    cout << "M1 (123.45): " << m1 << endl;

    Money sum = m1 + m2;  
    std::cout << "Sum: " << sum << std::endl;

    Money diff = m1 - m2;
    std::cout << "Difference: " << diff << std::endl;

    Money prod = m1 * m2;
    std::cout << "Product: " << prod << std::endl;

    Money quot = m1 / m2;
    std::cout << "Quotient: " << quot << std::endl;

    return  0;
}

底部是我正在运行的测试。第一个测试只是在任何操作之前打印我的 Money 变量之一。

我的输出:

M1 (123.45): 123.45
Sum: 22395.0
Difference: 2295.0
Product: 1240672.50
Quotient: 1.22

如您所见,第一个测试正确打印:123.45。然而,其他国家则将其全部印在美元面。我不明白为什么,我尝试更改我的数学运算符定义和我的 << operator definition. This is Chapter 9, Exercise 14.

c++ visual-c++ output
1个回答
0
投票

问题在于,例如,您的

operator+
函数使用
double
构造函数,它将值与
100
相乘。

因此,您使用值

(12345 + 10050) * 100
初始化新的货币对象。

您应该有一个私有构造函数,它接受

long int
参数并且不进行任何转换。

© www.soinside.com 2019 - 2024. All rights reserved.