-1

I'm writing a simple class in c++ simulating card payments and doing simple arithmetic operations and the compiler converts my double variable to int. In my class I have a makePayment method which returns double and it is working fine. The problem comes when I try to charge my card and somehow it appears like the balance variable in the class changes from double to int, because after I charge my card every operation or when I print the balance it returns an integer.

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

};

and here are the tests I do in the main function

   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

I really can't wrap my head around why is that happening, so if someone could explain me, it will be highly appreciated.

1 Answers1

1

set::precision(3) is asking for 3 digits in the output.

And that's what you get.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203