If else statement loop or repeat until true - c++

I'm not sure how to loop or repeat a cin >> cashTendered if the amount tendered is less than the required amount.
So far, this is what I have.
if (cashTendered > || == total)
{
cout << "Your change is: $" << fixed << setprecision(2) << change << ".\n\n"
<< "Have a great day!\n\n\n\n\n";
}
else
{
cout << "You did not tender enough money to cover the total cost.\n"
<< "Please enter amount of cash tendered: $";
}
So now I want the if statement to repeat until true.
any suggestions?

Have a look at loops in c++. Also if condition can be shortened to >= instead of > || ==. Moreover, since you want to repeat until the cashTendered is >= total, you need a loop that checks the condition if cashTendered is < total.
while (cashTendered < total)
{
cout << "You did not tender enough money to cover the total cost.\n"
<< "Please enter amount of cash tendered: $";
cin >> cashTendered;
}
cout << "Your change is: $" << fixed << setprecision(2) << change << ".\n\n"
<< "Have a great day!\n\n\n\n\n";

while(true)
{
cin >> cashTendered
if (cashTendered >= total)
{
cout << "Your change is: $" << fixed << setprecision(2) << change << ".\n\n"
<< "Have a great day!\n\n\n\n\n";
break;
}
else
{
cout << "You did not tender enough money to cover the total cost.\n"
<< "Please enter amount of cash tendered: $";
}
}

Related

I am having problems with rejecting negatives within my function

I was doing a school assignment involving functions, it wasn't too hard until I learned I needed to reject negative numbers as variables. It doesn't reject the numbers and instead just skips the next variable and then will loop to a seemingly random variable random variables in the code when the function completes.
void InPatient()
{
int DaysIn = 0;
double DailyRate{};
double MedicationCharges{};
double ServiceCharges{};
cout << "Please enter number of days patient stayed (Rounded up):" << endl;
cin >> DaysIn;
//I tried to use while statements to solve this problem and it hasn't worked
while (DaysIn != 50000000000)
{
if (DaysIn >= 0)
{
cout << "Please enter hospital's daily rate as a decimal (Ex: .35, .265):" << endl;
cin >> DailyRate;
}
else if (DaysIn < 0)
{
cout << "That is not a valid number in the system" << endl;
}
if (DailyRate >= 0)
{
cout << "Please enter medicine charges:" << endl;
cin >> MedicationCharges;
}
else if (DailyRate < 0)
{
cout << "That is not a valid number in the system" << endl;
}
//I tried these else if statements to reject negative numbers and loop back but it just says "It doesn't work" and continues on.
if (MedicationCharges >= 0)
{
cout << "Please enter service charges (for lab testing or whatnot):" << endl;
cin >> ServiceCharges;
}
else if (MedicationCharges < 0)
{
cout << "That is not a valid number in the system" << endl;
}
if (ServiceCharges >= 0)
{
double DaysInFee = DaysIn / DailyRate;
double HospitalBill = DaysInFee + MedicationCharges + ServiceCharges;
cout << "Patient's Stay Fee: $" << DaysInFee << "\n";
cout << "Medication Charges: $" << MedicationCharges << "\n";
cout << "Service Charges: $" << ServiceCharges << "\n";
cout << "Patient's total is $" << std::setprecision(2) << std::fixed << HospitalBill << " " << "today." << endl;
}
else if (ServiceCharges < 0)
{
cout << "That is not a valid number in the system" << endl;
}
}
}
void OutPatient()
{
double MedicationCharges = 0;
double ServiceCharges{};`
//I've done something different down here, but it does the exact same thing
while (MedicationCharges != 50000000000)
{
cout << "Please enter medicine charges:" << endl;
cin >> MedicationCharges;
cout << "Please enter service charges (for lab testing or whatnot):" << endl;
cin >> ServiceCharges;
double HospitalBill = MedicationCharges + ServiceCharges;
cout << "Medication Charges: $" << MedicationCharges << "\n";
cout << "Service Charges: $" << ServiceCharges << "\n";
cout << "Patient's total is $" << std::setprecision(2) << std::fixed << HospitalBill << " " << "today." << endl;
if (MedicationCharges < 0)
{
cout << "That is not a valid number in the system" << endl;
}
//These just say "These don't work" but let's the code use them anyways.
else if (ServiceCharges < 0)
{
cout << "That is not a valid number in the system" << endl;
}
}
}
As stated in the code, I have used while and if statements to reject negatives, but it doesn't reject them.
Add a continue in your else if blocks to restart the while-loop after an incorrect input
Alternatively, add a break or return statement to leave the loop or function. It depends what you want to do in the error case.

C++ looping issues

I am having difficulty locating and solving a bug in my basic ATM program. The issue manifests in the withdrawal option of both the checking and savings accounts. After the account has zero available funds it will allow the user to enter a negative number essentially over-drafting the account. I am trying to prevent this from happening.
Additionally, if there are zero funds available to withdraw the program continues to loop, thereby not allowing the user to utilize the menu to select a different option.
I have provided examples of the screen output illustrating the issues and the some of the source code.
Issue
Issue
#include <iomanip>
#include <iostream>
using std::cin;
using std::cout;
double checking_balance = 2500.00, savings_balance = 1000.00, savings_amount,
checking_amount;
int menu;
int main() {
do {
// Main Menu
cout << std::fixed << std::setprecision(2);
cout << "\n";
cout << "\tWelcome to Seabreeze Bank\n";
cout << "*********************************\n\n";
cout << "1. Savings Account\n";
cout << "2. Checking Account\n";
cout << "3. Quit\n\n";
cin >> menu;
cout << "\n\n";
// User validation for the Main Menu
if (menu < 1 || menu > 3) {
cout << "You have entered an invalid option.\n";
cout << "Please enter a number 1-3 > ";
cin >> menu;
cout << "\n\n";
}
switch (menu) {
case 1:
int savings_menu;
do {
// Savings Account Menu
cout << "\t\tSavings Account\n\n";
cout << "Please enter a menu item (1-3) >\n";
cout << "*********************************\n";
cout << "1. Withdrawal\n";
cout << "2. Deposit\n";
cout << "3. Main Menu\n";
cout << "\n\n";
cin >> savings_menu;
cout << "\n";
// Withdrawal selection for Savings Account
if (savings_menu == 1) {
cout << "How much would you like to withdraw from your savings "
"account: ";
cin >> savings_amount;
cout << "\n";
while (savings_balance < savings_amount) {
cout << "You do not have enough funds in your account to withdraw "
"that much\n";
cout << "Please enter a smaller amount: ";
cin >> savings_amount;
cout << "\n";
}
while (savings_amount <= 0) {
cout << "Please enter an amount greater than 0: ";
cin >> savings_amount;
}
savings_balance -= savings_amount;
cout << "Your Savings Account Balance: " << savings_balance << "\n\n";
if (savings_balance == 0) {
cout << "You now have zero funds in your Savings Account.\n\n";
}
}
This is a floating point arithmetic problem.
In general, floating point arithmetic is not exact because of rounding errors, saving_amount is not equal to 0 but it is almost equal to 0.
I prefer the casting option because in certain cases using the round() function will need a bit more modification if the result is negative.
Instead of "while (savings_amount <= 0)" you should use while (int(saving_amount) <= 0). Similarly you have to do casting where you are using conditional operator in your program.
To prevent entering negative number to withdraw, you have to put an "if" statement to check if number is negative.

Cases and Switch Issue

I am writing a program that simulates an ATM. So it tracks account balances, withdrawals and deposits in a very basic matter.
Everything works well during the first iteration, but if I go to make two or more deposits or withdrawals, the account balances default back to the original amount.
Here is an example of what is currently happening: I have $1,000 in my account initially. I make a deposit of $50. It prints out that I now have $1,050 in my account and asks if I would like to perform any other actions. (This is all good). If I select that I want to make another deposit of $100, it says my new account balance is $1,100 instead of $1,150. It does not store my latest account balance when I perform new withdrawals or deposits.
The second (less important) issue is that each time a withdrawal is made, there is a $2.50 fee for each withdrawal that also gets subtracted from my account balance.
I have not learned loops yet, only Cases, If statements and If Else Statements.
Is it possible to do what I want to do? Below is my code. Thank you in advance! This is my first time posting, so if I have pasted my code wrong, I apologize.
#include <iostream>
#include <string>
using namespace std; // opens library for "cout"
int main()
{
float test;
int logout;
string name;
float balance;
float fee;
int choice;
float withdraw;
float deposit;
float bonus;
bonus = 2.50;
balance = 1572.36;
fee = 12.50;
char answer;
cout << "Hello, thank you for banking with Pallet Town Bank.\n";
cout << "Please enter your name. ";
cin >> name;
cout << "Hello " << name << ". Your current balance is $" << balance << ".\n";
cout << "There will be a a service fee of $12.50 subtracted from your "
"account.\n";
cout << "Your updated balance will be $" << balance - fee << " \n";
cout << "What would you like to do today?\n";
do
{
cout << "\n1 - Current Balance\n2 - Withdraw\n3 - deposit\n4 - Log "
"Out\nOption: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "\nCurrent Balance is " << balance - fee - withdraw + deposit
<< " \n";
cout << "Would you like to take any other actions today?\n";
break;
case 2:
cout << "\nWithdraw - How much would you like to withdraw? $";
cin >> withdraw;
cout << "Your new balance after withdrawing $" << withdraw << " will be $"
<< balance - fee - withdraw + deposit << "\n";
cout << "Would you like to take any other actions today?\n";
break;
case 3:
cout << "\nDeposit - How much would you like to deposit? $";
cin >> deposit;
test = balance - fee - withdraw + deposit;
cout << "Your new balance after depositing $" << deposit << " will be $"
<< test << endl; //<<balance - fee - withdraw + deposit<<"\n";
cout << "Would you like to take any other actions today? Y or N \n";
cin >> answer;
cout << answer;
if (answer == 'y' || 'Y')
{
test = balance - fee - withdraw + deposit + deposit;
cout << "Your new balance after depositing $" << deposit << " will be $"
<< test << endl;
}
// cout <<"Your new balance after depositing $"<<deposit<<" will be $"
// <<test<< endl; //<<balance - fee - withdraw + deposit<<"\n";
// cout <<"Would you like to take any other actions today?\n";
break;
case 4:
cout << "\nLog Out - Thank you for banking with Pallet Town Bank. Have "
"a great day!";
}
} while (choice != 4);
}
The main issue, as Alan Birtles points out, is that you never update the balance value; you just store the temporary calculations in the test variable.
Here's how you could change your code. I tried interpreting the expected behaviour of the program as best I could from the text:
#include <iostream>
#include <string>
using namespace std;
int main()
{
const double fee = 12.50;
double balance = 1572.36;
cout << "Hello, thank you for banking with Pallet Town Bank.\n";
cout << "Please enter your name. ";
string name;
cin >> name;
cout << "Hello " << name << ". Your current balance is $" << balance << ".\n";
cout << "There will be a a service fee of $12.50 subtracted from your "
"account.\n";
cout << "Your updated balance will be $" << (balance -= fee) << " \n";
cout << "What would you like to do today?\n\n";
while (true)
{
cout << "1 - Current Balance" << '\n'
<< "2 - Withdraw" << '\n'
<< "3 - deposit" << '\n'
<< "4 - Log Out" << '\n'
<< "Option: ";
int choice;
cin >> choice;
cout << endl;
if (choice == 4) break;
switch (choice)
{
case 1:
cout << "Current Balance is " << balance << '\n';
break;
case 2:
cout << "Withdraw - How much would you like to withdraw? $";
double withdraw;
cin >> withdraw;
cout << "Your new balance after withdrawing $" << withdraw << " will be $"
<< (balance -= withdraw) << '\n';
break;
case 3:
cout << "Deposit - How much would you like to deposit? $";
double deposit;
cin >> deposit;
cout << "Your new balance after depositing $" << deposit << " will be $"
<< (balance += deposit) << '\n';
break;
}
cout << "Would you like to take any other actions today? ";
char answer;
cin >> answer;
cout << endl;
if (toupper(answer) == 'N') break;
}
cout << "Log Out - Thank you for banking with Pallet Town Bank. Have a great day!" << endl;
}
Live demo
Changes
First of all, every time a modification is made (withdrawal/deposit), we need to actually update the balance. We can do so by using the += or -= operators (called "compound assignment" operators): when writing balance += x, we're adding x to balance, and when writing balance -= x we're subtracting. These expressions are equivalent to balance = balance + x and balance = balance - x, respectively.
I moved the "Would you like to [...]" part outside the switch statement, to avoid repeating it in each case.
As pointed out in the comments, answer == 'Y' || 'y' isn't the same as answer == 'Y' || answer == 'y'. I changed that to toupper(answer) == 'Y'.
I moved the logout handling outside the while loop, so that whenever the loop terminates, the logout message is always shown. That allows us to remove case 4 from the switch statement, by checking at the beginning if choice == 4 and then breaking out of the loop accordingly. This also implies the loop becomes a while (true) loop. Probably there is a more elegant way.
Even better
If you're confortable with functions, I would suggest refactoring the code, isolating each operation individually:
#include <iostream>
#include <string>
#include <sstream>
#include <cmath>
using namespace std;
const int FEE = 1250; // fee in cents
//---- Utilities ----//
string moneyString(int cents) {
ostringstream oss;
oss << cents/100 << '.' << cents % 100;
return oss.str();
}
int toCents(double money) {
return int(round(money*100));
}
int getMoney() {
double money;
cin >> money;
return toCents(money);
}
//---- User input ----//
// Available choices
enum Choices {
BALANCE = 1,
WITHDRAW = 2,
DEPOSIT = 3,
LOGOUT = 4
};
short int getChoice() {
short int choice = 0;
while (choice < 1 or choice > 4) {
cout << "1 - Current Balance" << '\n'
<< "2 - Withdraw" << '\n'
<< "3 - deposit" << '\n'
<< "4 - Log Out" << '\n'
<< "Option: ";
string input;
cin >> input;
choice = atoi(input.c_str());
cout << endl;
}
return choice;
}
bool userWantsMoreActions() {
cout << "Would you like to take any other actions today? ";
char answer;
cin >> answer;
cout << endl;
return toupper(answer) == 'Y';
}
//---- Actions ----//
void greeting(double &balance) {
cout << "Hello, thank you for banking with Pallet Town Bank.\n";
cout << "Please enter your name. ";
string name;
cin >> name;
cout << "Hello " << name << ". Your current balance is $" << moneyString(balance) << ".\n";
cout << "There will be a a service fee of $12.50 subtracted from your account.\n";
cout << "Your updated balance will be $" << moneyString(balance -= FEE) << " \n";
cout << "What would you like to do today?\n\n";
}
void printBalance(const double &balance) {
cout << "Current Balance is " << balance << '\n';
}
void withdraw(double &balance) {
cout << "Withdraw - How much would you like to withdraw? $";
int withdraw = getMoney();
cout << "Your new balance after withdrawing $" << withdraw << " will be $"
<< (balance -= withdraw -= FEE) << '\n';
}
void deposit(double &balance) {
cout << "Deposit - How much would you like to deposit? $";
int deposit = getMoney();
cout << "Your new balance after depositing $" << moneyString(deposit)
<< " will be $" << moneyString(balance += deposit -= FEE) << '\n';
}
int main()
{
// Initialize a sample session:
double balance = 157236;
greeting(balance);
while (true)
{
short int choice = getChoice();
if (choice == Choices::BALANCE) printBalance(balance);
else if (choice == Choices::WITHDRAW) withdraw(balance);
else if (choice == Choices::DEPOSIT) deposit(balance);
else if (choice == Choices::LOGOUT) break;
if (not userWantsMoreActions()) break;
}
cout << "Log Out - Thank you for banking with Pallet Town Bank. Have a great day!" << endl;
}
Live demo

Car Loan Calculation (C++)

My objective is to calculate and output a loan repayment schedule. The thing I would like to get help on is putting the principles added to the equation and printing out the repayment schedule. I am not sure if I did the calculations right as I have not had a personal finance class yet, and still get to grasp the concept of loans.
The loan repayment schedule is based on full price of an auto, their interest rate and their payment, assuming no money is put down. All fees and taxes are included in the price and will be financed. I also have to out put the repayment schedule to both the screen and a file - one month per line. . If the user has a credit rate of 800, they get a 3% annual interest rate; 700+ gets 5% interest rate; 600+ get 7% interest rate; and less than 600 get 12% interest rate
The credit scores for 700, 600, and below 600 are left blank because I am just going to copy the 800 credit score part again but change the interest rates.
// This program calculates a loan depending on the pereson's credit score
// how much they can pay per month. It almost outputs the month, principal,
// payment, interest, and the money that's been applied
#include <iostream>
#include <cstdio>
#include <iomanip>
using namespace std;
int main() {
int month = 0, creditScore = 0, whichCar;
double principle, payment = 0.0, interestPaid, applied, interestRate;
cout << fixed << setprecision(2) << showpoint; // Sets total or whatever to 2 decimal points
cout << "---------------------------------------------" << endl; // Displays welcome banner
cout << "| |" << endl;
cout << "| JOLLY GOOD SHOW WE HAVE CARS AYEEE |" << endl;
cout << "| |" << endl;
cout << "---------------------------------------------" << endl;
cout << endl;
cout << "Hey, I see you want a car. You can only purchase one car though." << endl;
cout << endl;
cout << "1. Furawree: $6,969.69" << endl; // Displays menu of autos
cout << "2. Buggee: $420,420.420" << endl;
cout << "3. Sedon: $900" << endl;
cout << "4. Truck: $900,000.90" << endl;
cout << "5. Couppee: $22,222.22" << endl;
cout << endl;
cout << "Which car would you like to purchase?" << endl; // Asks user car type and user inputs car #
cout << "Please enter the number of the car: ";
cin >> whichCar;
cout << endl;
switch(whichCar) { // If user choses a number 1-5, then it asks them how much they can pay each month for the car and their credit score
case 1: // FURAWREE
principle = 6969.69;
break;
case 2: // BUGGEE
principle = 420420.42;
break;
case 3: // SEDON
principle = 900;
break;
case 4: // TRUCK
principle = 900000.90;
break;
case 5: // COUPPEE
principle = 22222.22;
break;
default: // If user doesn't pick a number from 1-5
cout << "Yea uhhmmm we don't have that sorry, go away." << endl;
}
cout << "Please enter how much you can pay each month for this Furawree: ";
cin >> payment;
cout << "Please enter your credit score: ";
cin >> creditScore;
if (creditScore >= 800) {
interestRate = .03 / 12;
do {
interestPaid = principle * interestRate;
applied = payment - interestPaid;
month++;
} while (principle < 0) ;
cout << "Month " << " Principle " << " Payment " << " Interest " << " Applied " << endl;
cout << month << " $" << principle << " $" << payment << " " << interestPaid << " $" << applied << endl;
} else if (creditScore >= 700) {
// Will be copied from the 800 credit score
} else if (creditScore >= 600) {
// Will be copied from the 800 credit score
} else {
// Will be copied from the 800 credit score
}
cout << endl;
cout << endl;
cout << "Your payment: $" << payment << endl;
cout << "Your credit score: " << creditScore << endl;
cout << endl;
cout << endl;
system("pause");
return 0;
}
Mate, you need to fix code under credit - 800.
loop condition is incorrect
cout is after the loop, therefore it will print only once .
principle is not incremented nor decremented . and you are checking if principle is less than 0, however principle is set more than 0. so the loop will execute only once.
you need a fix some thing like this. I have just fine tuned little bit. pls fix the rest
if (creditScore >= 800) {
interestRate = .03 / 12;
cout << "Month " << " Principle " << " Payment " << " Interest " << " Applied " << endl;
cout <<"-------------------------------------------------------" << endl;
do {
interestPaid = principle * interestRate;
applied = payment - interestPaid;
principle = principle - applied;
cout << month << " $" << principle << " $" << payment << " " << interestPaid << " $" << applied << endl;
month++;
} while (principle > 0) ;
} else if (creditScore >= 700) {
Note :-
The above code is not following any object oriented concepts. Its not even functional programming. Introduce classes, methods to reduce headache and it will help to debug.
use \t\t to get spaces instead of spaces.
This code will need a big re-work to make it look professional .

Can't get an int to update outside of the while loop

When it runs the winnings or losses are taken or added from the bank and then it is run again the bank is set back to a 25$ bank not the updated bank
int main()
{
srand(time(0));
int bank = 25;
int total;
char answer;
cout << "Come play Spin the Wheel. The wheel has numbers from 1-10." << endl
<< "If you spin an even number you lose that amount. If you spin" << endl
<< "an odd number you win that amount. You start with a 25$ bank." << endl;
cout << "Your bank is $" << bank << ". Would you like to spin the wheel? (y/n):" << endl;
cin >> answer;
while (toupper(answer) == 'Y')
{
int num = rand() % 10 + 1;
if (bank <= 10)
{
cout << "Sorry you must have more than 10$ to play" << endl;
}
else if (num % 2 == 0 )
{
total = bank + num;
cout << "You spun a " << num << " and won $" << num << endl;
cout << "Your bank is now: $" << total << endl;
}
else
{
total = bank - num;
cout << "You spun a " << num << " and lost $" << num << endl;
cout << "Your bank is now: $" << total << endl;
}
cout << "Would you like to play Again (y/n) ?" << endl;
cin >> answer;
}
return 0;
}
When it runs the winnings or losses are taken or added from the bank and then it is run again the bank is set back to a 25$ bank not the updated bank
You initialize bank to be 25 dollar in this function. Inside the while loop only total is updated not bank.
Another problem arises when there is too few money to play. I suppose you would like to display your message one time, but you are stuck inside the loop because it is never broken out of.
I believe your else if and else statements are backwards.
num % 2 == 0
Would signify that the number was even, if true. The instructions say that you lose the money if the number is even.
Bank will never be less than or equal to 10 because you are never setting bank to anything after the initial 25. Its always 25.
The variable total seems redundant. Maybe add or subtract the amount rolled directly from bank.
You need to set
bank = total
else you never change its value