2016-12-02 162 views
-1

我在C++中編寫了一個簡單的類,用於模擬卡支付並執行簡單的算術運算,編譯器將我的雙變量轉換爲int。在我的班級中,我有一個makePayment方法,返回double,它工作正常。問題來了,當我嘗試charge我的卡,不知何故,它看起來像balance類變量從doubleint,因爲我charge我的卡每次操作或當我打印balance它返回一個整數。C++編譯器從double轉換爲int

class DebitCard { 

public: 

    DebitCard(); 

    bool makePayment(double amount); 

    const double& getBalance() 
     { return balance; } 

    void dailyInterest() 
     { balance *= interest; } 

    void chargeCard(double amount) 
     { balance += amount; } 

private: 

    string card_number; 
    short pin; 
    double balance; 
    double payment_fee; // percentage fee for paying with the card 
    double interest;  // daily interest 
    //double charge_tax;  // percentage taxing for charing the card 

}; 

,這裏是我的主要功能做測試

DebitCard d; // balance is set to 100 

    d.makePayment(91.50); 
    cout << std::setprecision(3) << d.getBalance() << endl; // 7.58 

    d.chargeCard(200); 
    cout << std::setprecision(3) << d.getBalance() << endl; // 208 

    d.makePayment(91.50); 
    cout << std::setprecision(3) << d.getBalance() << endl; // 115 

我真的不能換我周圍這是爲什麼發生的,因此,如果有人可以解釋我來說,這將是非常頭讚賞。

+0

[std :: showpoint,std :: noshowpoint](http://en.cppreference.com/w/cpp/io/manip/showpoint) – crashmstr

+0

http://en.cppreference.com/w/cpp/ io/ios_base/precision:「管理浮點輸出的精度(即***生成多少位數***)...」 –

+0

bool makePayment(double amount); ??實施? – eyllanesc

回答

1

set::precision(3)要求輸出中有3位數字。

這就是你得到的。

+0

明白了,std :: fixed修復了它:)謝謝你的快速回復! –