我正在努力学习使用名称空间声明比使用"使用命名空间标准"更明确.我正在尝试将我的数据格式化为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';
}
Run Code Online (Sandbox Code Playgroud)
在Visual Studio 2008上,当我运行程序时,在我想要的数据之前得到输出"8192".这有什么理由吗?
另外,我认为我没有正确设置固定部分或2位小数,因为一旦我添加了setprecision(2),我似乎得到了科学记数法.谢谢.
你想要的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';
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6380 次 |
| 最近记录: |