6

我正在尝试学习使用命名空间声明,而不是仅仅说“使用命名空间标准”。我正在尝试将我的数据格式化为小数点后 2 位,并将格式设置为固定且不科学。这是我的主文件:

#include <iostream>
#include <iomanip>

#include "SavingsAccount.h"
using std::cout;
using std::setprecision;
using std::ios_base;

int main()
{
    SavingsAccount *saver1 = new SavingsAccount(2000.00);
    SavingsAccount *saver2 = new SavingsAccount(3000.00);

    SavingsAccount::modifyInterestRate(.03);

    saver1->calculateMonthlyInterest();
    saver2->calculateMonthlyInterest();

    cout << ios_base::fixed << "saver1\n" << "monthlyInterestRate: " << saver1->getMonthlyInterest()
        << '\n' << "savingsBalance: " << saver1->getSavingsBalance() << '\n';
    cout << "saver2\n" << "monthlyInterestRate: " << saver2->getMonthlyInterest()
        << '\n' << "savingsBalance: " << saver2->getSavingsBalance() << '\n';
}

在 Visual Studio 2008 上,当我运行我的程序时,我在想要的数据之前得到“8192”的输出。这有什么原因吗?

另外,我认为我没有正确设置固定部分或小数点后 2 位,因为一旦添加了 setprecision(2),我似乎就得到了科学记数法。谢谢。

4

3 回答 3

5

您想要std::fixed(另一个只是将其值插入流中,这就是您看到 8192 的原因),而且我std::setprecision在您的代码中的任何地方都没有看到调用。
这将解决它:

#include <iostream>
#include <iomanip>

using std::cout;
using std::setprecision;
using std::fixed;

int main()
{
    cout << fixed << setprecision(2)
         << "saver1\n" 
         << "monthlyInterestRate: " << 5.5 << '\n' 
         << "savingsBalance: " << 10928.8383 << '\n';
    cout << "saver2\n" 
         << "monthlyInterestRate: " << 4.7 << '\n' 
         << "savingsBalance: " << 22.44232 << '\n';
}
于 2010-04-28T06:34:46.800 回答
3

It might not be the answer you're looking for, but floating-point numbers are not suited to financial calculations because fractions like 1/100 cannot be represented exactly. You might be better off doing the formatting yourself. This can be encapsulated:

class money {
    int cents;
public:
    money( int in_cents ) : cents( in_cents ) {}

    friend ostream &operator<< ( ostream &os, money const &rhs )
        { return os << '$' << m.cents / 100 << '.' << m.cents % 100; }
};

cout << money( 123 ) << endl; // prints $1.23

Better(?) yet, C++ has a facility called the monetary locale category which includes a money formatter which takes cents as an argument.

locale::global( locale("") );
use_facet< money_put<char> >( locale() ).put( cout, false, cout, ' ', 123 );

This should Do the Right thing internationally, printing the user's local currency and hiding the number of decimal places from your implementation. It even accepts fractions of a cent. Unfortunately, this does not seem to work on my system (Mac OS X), which has generally poor locale support. (Linux and Windows should fare better.)

于 2010-04-28T06:39:21.727 回答
2
cout << setiosflags(ios::fixed) << setprecision(2) << 1/3.;

ios_base::fixed不是操纵器,它是1 << 13ios 标志的值 ()。

于 2010-04-28T06:25:29.577 回答