简体   繁体   中英

Why does my program not return 0 in an if statement?

My program is not returning 0 when I press n when it asks me if I want to accept the charges.

I want the program to stop when I press n and run the $25 charge when I press y

Can someone please explain to me what I'm doing wrong?

#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdlib>

using namespace std;

int main()
{
    double InitialAmount, WithdrawAmount; 

    cout << fixed << setprecision(2);

    cout << "Deposite initial amount: ";
    cin >> InitialAmount;
    if (cin.fail())
    {
        cin >> InitialAmount;
        cout << "Invalid initial amount" << endl;
        return 0;
    }

    if (InitialAmount < 0)
    {
        cout << "Balance under 0, cannot withdraw" << endl;
        return 0;
    }

    cout << "Enter an amount to withdraw: ";
    cin >> WithdrawAmount;
    if (cin.fail())
    {
        cin >> WithdrawAmount;
        cout << "Invalid withdraw amount" << endl;
        return 0;
    }

    if (WithdrawAmount > 500)
    {
        cout << "Cannot withdraw this amount" << endl;
        return 0;
    }

    double YesFees, InsufFees;

    if (InitialAmount > 1 and WithdrawAmount > InitialAmount)
    {
        cout << "Insufficient funds for this withdrawal There will be a $25.00 service charge. Would you like to continue? (Y/N): ";
        cin >> InsufFees;


        if (InsufFees == 'y')
        {
            YesFees = 25;
        }

       if (InsufFees == 'n')
       {
          return 0;
       }

    }

    double fees;
    if (WithdrawAmount > 300)
    {
        fees = WithdrawAmount * .04;
    }

    cout << left << setw(20) << setfill('.') << "Amount withdrawn";
    cout << "$" << setw(10) << setfill (' ') << right << WithdrawAmount << endl;
    cout << left << setw(20) << setfill('.') << "Amount of fees";
    cout << "$" << setw(10) << setfill (' ') << right << fees + YesFees << endl;
    cout << left << setw(20) << setfill('.') << "Balance";
    cout << "$" << setw(10) << setfill (' ') << right << InitialAmount - WithdrawAmount - YesFees - fees  << endl;

return 0;
}

The InsufFees variable is of type double , so cin is failing when it tries to read a character. You need to change the type of InsufFees to char :

char InsufFees;
cin >> InsufFees;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM