C++编译器从double转换为int

问题描述:

我在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

set::precision(3)要求输出中有3位数字。

这就是你得到的。

+0

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