help the beginner

my program is very simple:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include "bank_acc.h"
using namespace std;

int main(){
    newBankAcct nba(1001, 0, 0.1);

    nba.print();
    //cout << "Acct Num: " << ba.getAcctNum() << endl;
    cout << "Specify operation: 1 for withdraw, 2 for deposit, 3 for pay interest, 4 for exit" << endl;

    while (true){
        int choice;

        cin >> choice;
        if (choice == 4){
            break;
        } else if (choice == 3){
            nba.payInterest();
        } else {
            double amt;
            cin >> amt;
            //if (choice == 1){
              //  if (nba.withdraw(amt) == false)
              if (choice == 1 && (nba.withdraw(amt) == false)){
                    cout << "Not enough balance" << endl;
            } else{
                nba.deposit(amt);
            }
        }

        cout << "Balance: " << nba.getBalance() << endl;        
    }
    
    return 0;
}


here is the definition of withdraw method:
1
2
3
4
5
6
7
bool bankAcct::withdraw(double amt){
    if (amt > _balance)
        return false;
    _balance -= amt;
    return true;
}


the peculiarity is that when i withdraw an amount of money less than balance, the balance isn't deducted. the problem lies in the code underlined in the main() function. when I change this line to the commented two lines above, the problem disappears. can anyone explain why? i think the former and the latter are the same.
thanks.
It IS being withdrawn, but then you deposit it again immediately afterwards.

The 'else' clause on line 27 will trigger if the previous 'if' clause results in false.

What's happening with you is that nba.withdraw is returning true (Because the withdraw was successful). This results in the if() clause being false, which triggers the else clause which does a deposit.


Don't try to get clever with compounded if statements. Get rid of the && on line 25 and just put another if statement in there.
Topic archived. No new replies allowed.