When i input a a negative integer, the it does break which is what i want but when i input a positive integer, it still breaks. Any workarounds? If so, i also want to learn how will i be able to restart the program instead of terminating it instead? I'm just starting out C++ so yeah :)
#include <iostream>
usingnamespace std;
//* Variables declared below (int, double, float).
double remainBal; // remaining balance after deduction of purchased laptop from income
main()
{
// Determining the user's income.
cout << "How much do you earn yearly? $";
double getIncome;
cin >> getIncome;
while(true) // rest of the code must be inside the 'while' statement in order to use the 'break' statement.
{
if (getIncome < 0)
cout << "You have entered an invalid amount."; break;
if (getIncome > 10000) // If user earns more than $10k a year.
cout << "You earn more than $10,000 a year. \n";
elseif(getIncome < 10000) // If user earns less than $10k a year.
cout << "You earn less than $10,000 a year. \n";
else
cout << "You earn exactly $10,000 a year! \n"; // If user earns $10k a year.
// Selection of available laptops for sale
cout << "Select which laptop brand would you like to purchase\n";
cout << "1) Dell - $15,000\n";
cout << "2) Asus - $ 7,000\n";
cout << "Your choice: ";
int LaptopSelection;
cin >> LaptopSelection;
// If Dell was selected
if (LaptopSelection == 1)
{ remainBal = getIncome - 15000;
{ if (remainBal > 0) // if Dell is affordable
cout << "You have $" << remainBal << "left.";}
if (remainBal < 0) // if Dell is not affordable
cout << "Sorry, you do not have enough cash in order to make a purchase."; }
else
// If Asus was selected
if (LaptopSelection == 2)
{ remainBal = getIncome - 7000;
{ if (remainBal > 0) // if Asus is affordable
cout << "You have $" << remainBal << "left.";}
if (remainBal < 0) // if Asus is not affordable
cout << "Sorry, you do not have enough cash in order to make a purchase."; }
} // End of while statement.
/* The statement 'break' ends the program (goes to 'return 0') */
/* if the input entered is a negative integer */
return 0;
}
Line 17: Only the cout is conditional on the if statement. If you want multiple statements to be conditional on the if statement, you must use {} around the statements.
1 2 3 4
if (getIncome < 0)
{ cout << "You have entered an invalid amount.";
break;
}
PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post. http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
if you want the program to restart put the portion of code that you want to repeat in a while loop and create a bool which is true i.e bool userContinue = true; which is outside of the while loop. Inside your while loop ask if they would like to continue. If their inout indicates they would not make userContinue = false and it will break out of the while loop ending the program.