2010-04-28 52 views
7

我試圖學習使用命名空間聲明比不只是說「使用命名空間標準」。我試圖將我的數據格式化爲2位小數,並將格式設置爲固定而不科學。這是我的主要文件:格式,iomanip,C++

#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)後得到了科學記數法。謝謝。

回答

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'; 
} 
2
cout << setiosflags(ios::fixed) << setprecision(2) << 1/3.; 

ios_base::fixed不操縱器它是用於IOS標誌的值(1 << 13)。

3

它可能不是你要找的答案,但浮點數不適合的財務計算,因爲像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 OS X),它通常對語言環境支持較差。 (Linux和Windows應該更好。)

+0

'money_put' variant在我的機器上打印'123'而不是'$ 1.23'。它在任何語言環境中都不應該是可接受的輸出。 – jfs 2010-04-28 09:44:43

+0

@ J.F。 - 預期產出是$ 1.23'。你在使用什麼平臺? – Potatoswatter 2010-04-28 16:15:34

+0

@Patatoswatter:http://codepad.org/EY5PqSIw – jfs 2010-04-29 08:35:09