我正在努力学习如何使用名称空间声明,而不仅仅是简单地说“使用名称空间标准”。我尝试将我的数据格式化为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 Studio2008上,当我运行我的程序时,在我想要的数据之前得到一个"8192“的输出。这有什么原因吗?
此外,我认为我没有正确设置固定部分或2个小数位,因为一旦我添加了setprecision(2),我似乎就得到了科学记数法。谢谢。
发布于 2010-04-28 14:34:47
您需要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-28 14:39:22
这可能不是你想要的答案,但是浮点数不适合金融计算,因为像1/100这样的分数不能精确地表示出来。你自己做格式化可能会更好。可以对其进行封装:
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更好的(?)然而,C++有一个名为货币区域设置类别的工具,其中包括一个以美分作为参数的money formatter。
locale::global( locale("") );
use_facet< money_put<char> >( locale() ).put( cout, false, cout, ' ', 123 );这应该在国际上做正确的事情,打印用户的本地货币,并对您的实现隐藏小数位数。它甚至可以接受一分钱的零头。不幸的是,这在我的系统(Mac )上似乎不起作用,因为它的地区支持通常很差。(Linux和Windows应该会发展得更好。)
发布于 2010-04-28 14:25:30
cout << setiosflags(ios::fixed) << setprecision(2) << 1/3.;ios_base::fixed不是操纵器,它是ios标志的值(1 << 13)。
https://stackoverflow.com/questions/2727139
复制相似问题