lundi 1 octobre 2018

Multiple if statements without an else C++

The code I have to write is basically a mini bank. It asks for an initial amount, the type of action and a second operator for that action. I'm not allowed to you else but am allowed to if statements (i don't understand why) nor am I allowed to use a loop or an array.

    #include <iostream>
#include <iomanip>
#include <string>
using namespace std;

int operand1;
int operand2;
float output;
char action;



int main()
{
   cout << fixed << showpoint << setprecision(2);

   cout << "Enter the initial balance [1-1000]: " << endl;
   cin >> operand1;

   cout << "Enter an action (D, W, I or C):" << endl;
   cin >> action;

   cout << "Enter the second operand:" << endl;
   cin >> operand2;


   if ((action != 'D' && action != 'W' && action != 'I' && action != 'C') || (operand1 > 1000 || operand1 < 1) || 
       (action == 'I' && operand2 > 15 || operand2 < 1) || (action == 'C' && operand2 != 20 && operand2 != 10 && operand2 != 5) ||
       (operand2 > 1000 || operand2 < 1))
   {
       cout << "Input out of range" << endl;
       return 0;
   }

   if (action == 'D')
   {
      output = (operand1 + operand2);
      cout << "The new account balance is " << output << endl;
   }

   if (action == 'W')
   {
      output = (operand1 - operand2);
      if (output<0)
      {
          cout << "Input out of range" << endl;
          return 0;
      }
       cout << "The new account balance is " << output << endl;
   }


   if (action == 'I')
   {

       output = ((float)operand1 + (((float)operand2 / 100) * (float)operand1));
       cout << "The new account balance is " << output << endl;
   }

   if (action == 'C')
   {
       output = operand1 % operand2;
       cout << operand1 / operand2 << " bills dispensed plus " << output << endl;
   }

    cin.get();
    cin.get();
    return 0;
}

This is the code so far. on certain instances i get multiple erros instead of just one. for example if input i should get: Enter the initial balance [1-1000]: 1030

Enter an action (D, W, I or C): D

Enter the second operand: 40

Input out of range

Input out of range, however, it seems to just move on when it sees the error anyway and I get the output:

Enter the initial balance [1-1000]:

1030

Input out of range

Enter an action (D, W, I or C):

D

Enter the second operand:

40

The new account balance is 1070.00

I can't seem to figure out to have only one output and for it to just display the error with no balance without using an else statement.

Aucun commentaire:

Enregistrer un commentaire