Home > Software design >  Why i'm getting overflow?
Why i'm getting overflow?

Time:03-29

I'm very new to c and still in the process of learning it. I've been assigned to create a simple bank simulator and just stumble upon a problem i can't seem to figure out for some reason. Whenever i try to check the balance it shows me some numbers and letters and my first thought was either it showed the memory adress or a overflow. I could deposit something first and it will be added to the balance variable and shows up in the program aswell without some awkward numbers and letters. My goal is to make sure that the balance is always showing a 0 until the user deposit or withdraw from it.

I somehow managed to fix this by using float instead of double, I'm not really sure why it worked at this point since I'm way to tired to even think about it, but I would rather use double since this program might use more data.

If anything seems unclear of what I'm trying to say I'll try and answer your question as soon as I can. I also add a image here to show you what I'm talking about.

#include <iostream>

using namespace std;

int main()
{
    while(true){
    cout << "[D]eposit\n";
    cout << "[W]ithdrawal\n";
    cout << "[B]alance\n";
    cout << "[I]nterest payment\n";
    cout << "[E]xit\n";
    char menu;
    double balance, deposit, withdraw;
    cin >> menu;
    switch(menu)
    {
    case'D':
        cout << "[DEPOSIT]\n" << "Deposit: ";
        cin >> deposit;
        balance  = deposit;
        continue;
    case'W':
        cout <<"[WITHDRAWAL]\n" << "Withdraw: ";
        cin >> withdraw;
        balance -= withdraw;
        continue;
    case'B':
        cout << "[BALANCE]\n" << "Amount: " << balance;
        continue;
    case'I':
        cout << "[INTEREST PAYMENT]\n";
        continue;
    case 'E':
        cout << "Program is closing...";
        break;
    default:
        cout << "Please use uppercase letters";
        continue;

    }
    break;
    }
    return 0;
}

CodePudding user response:

Balance isn't initialized, so when you add / substract an amount, the result is odd due to the random initial value of balance.

CodePudding user response:

Well the main reason for getting the gibberish data is because your balance variable is uninitialized, and accessing it is undefined behaviour.

You can fix it by doing this:

double balance = 0;
double deposit, withdraw;

Also, your program won't work as expected because you declare the balance variable inside the while loop. Just declaring the variables outside the loop will make it work as expected.

double balance = 0;
double deposit, withdraw;
while(true){
    ...
}
  •  Tags:  
  • c
  • Related