I am writing a "vending machine" program and I need to have 5 items where 3 items cost an integer amount and the other 2 cost a decimal amount.
I am only using if statements in this code, but there is an error with my cost variable.
What did I do wrong?
Code below:
#include <iostream>
using namespace std;
int main() {
cout << "Vending Machine" << endl;
cout << "----Items------" << endl;
cout << "1. Popcorn: $2" << endl;
cout << "2. Coconut Clusters: $3" << endl;
cout << "3. Granola Bar: $2.50" << endl;
cout << "4. Trail Mix: $1.50" << endl;
cout << "5. Chocolate: $1" << endl;
cout << "Enter you selection: " << flush;
int input;
cin >> input;
if (input == 1) {
cout << "You added Popcorn to your cart." << endl;
float cost = 2;
cout << "Your total is $" << cost << endl;
}
if (input == 2) {
cout << "You added Coconut Clusters to your cart." << endl;
float cost = 3;
cout << "Your total is $" << cost << endl;
}
if (input == 3) {
cout << "You added Granola Bar to your cart." << endl;
float cost = 2.50;
cout << "Your total is $" << cost << endl;
}
if (input == 4) {
cout << "You added Trail Mix to your cart." << endl;
float cost = 1.50;
cout << "Your total is $" << cost << endl;
}
if (input == 5) {
cout << "You added Chocolate to your cart." << endl;
float cost = 1;
cout << "Your total is $" << cost << endl;
}
cout << "Pay amount: " << flush;
float money;
cin >> money;
if (money > cost) {
float change = money-cost;
cout << "Thank you! You have $" << change << " change." << endl;
}
if (money == cost) {
cout << "Thank you! Have a nice day!." << endl;
}
if (money < cost) {
float amountOwed = cost-money;
cout << "Please insert another $" << amountOwed << endl;
cout << "Enter amount: " << flush;
float payment;
cin >> payment;
if (payment > amountOwed) {
float change2 = payment-cost;
cout << "Thank you! You have $" << change2 << " change." << endl;
}
if (payment == amountOwed) {
cout << "Thank you! Have a nice day!." << endl;
}
if (payment < amountOwed) {
cout << "Sorry, you did not enter enough money. Your cart has emptied." << endl;
}
}
return 0;
}
The problem is that you are doing the following:
int main()
{
[...]
if (input == 1) {
cout << "You added Popcorn to your cart." << endl;
float cost = 2;
cout << "Your total is $" << cost << endl;
}
[...]
if (money > cost) {
[...]
}
[...]
}
The scope of the variable cost is limited to the if block, because that is where you declare it. Therefore, the variable does not exist anymore when you evaluate the expression money > cost.
To fix this, you should instead declare the variable cost in the main block scope of the function, like this:
int main()
{
float cost;
[...]
if (input == 1) {
cout << "You added Popcorn to your cart." << endl;
cost = 2;
cout << "Your total is $" << cost << endl;
}
[...]
if (money > cost) {
[...]
}
[...]
}
Update: you've just changed your question to add float cost = 0; in a suitable place. Now you need to remove the float keyword from the attempted assignments inside each if (input == block: e.g. change float cost = 2.50; to cost = 2.50; so it changes the function-scope cost variable, instead of creating an extra if-scope variable.
Addressing your original problem...
Your if blocks...
if (input == 3) {
cout << "You added Granola Bar to your cart." << endl;
float cost = 2.50;
cout << "Your total is $" << cost << endl;
}
...each create a float cost variable local to the scope of that if, so after the } the value of cost that you set is gone. Instead, you need to have:
float cost;
Before your first if (input == ... statement, so its lifetime extends to the end of the enclosing function scope (i.e. until main() returns).
"Can I declare a variable in an “if statement”?"
Yes. For example:
if (auto foo = bar())
The variable foo will be valid inside the body of the if statement and will be initialized to whatever bar() returns and the body of the if will be entered if foo converts to a bool value of true.
Since C++17 you can also do:
if (auto foo = bar(); foo == 42)
Again, the variable foo will be declared and valid inside the if and initialized by bar(), but you now have more control over when to enter the if body.
When I try to compile your code, I get the following error message:
Error: ‘cost’ was not declared in this scope
In order to fix this error, you just need to declare cost variable in the function's main block scope, for example like this:
int main()
{
float cost;
[...]
}
Related
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.
I am working on the "checkout" process of my vending machine code. I want to write it so that the program will keep asking for the amount needed from the user until all the money is entered. However, this code segment does not completely work.
"Checkout" Segment of Code:
while (money < total) {
float amountOwed = total - money;
cout << "Please insert another $" << amountOwed << endl;
cout << "Enter amount: $" << flush;
float payment;
cin >> payment;
}
if (money > total) {
float change = money - total;
cout << "Thank you! You have $" << change << " change." << endl;
}
if (money == total) {
cout << "Thank you! Have a nice day!." << endl;
}
Full code below:
#include <iostream>
#include <iomanip>
using namespace std;
string menuItems[5] = { "Popcorn", "Coconut Clusters" , "Granola Bar" , "Trail Mix" , "Chocolate" };
float cost[5] = { 2, 3, 2.50, 1.50, 1 };
void vendingMachine() {
for (int i = 0; i < 5; i++)
cout << i + 1 << ". " << menuItems[i] << ": $" << cost[i] << endl;
}
int main() {
cout.precision(2);
cout << std::fixed;
cout << "Vending Machine" << endl;
cout << "----Items------" << endl;
vendingMachine();
cout << "Enter 0 to checkout" << endl;
float total;
total = 0;
int item;
do {
cout << "Enter your selection: " << flush;
cin >> item;
item = item - 1;
//here will be printed : $0 has been added to cart even if you pressed 0 and what to escape
//is it possible to fix this??
cout << menuItems[item] << ": $" << cost[item] << " has been added to cart." << endl;
total = total + cost[item];
} while (item != -1);
cout << " " << endl;
cout << "Proceding to checkout..." << endl;
cout << "========================" << endl;
cout << "Amount due: $" << total << endl;
cout << "Insert money here: $" << flush;
float money;
cin >> money;
while (money < total) {
float amountOwed = total - money;
cout << "Please insert another $" << amountOwed << endl;
cout << "Enter amount: $" << flush;
float payment;
cin >> payment;
}
if (money > total) {
float change = money - total;
cout << "Thank you! You have $" << change << " change." << endl;
}
if (money == total) {
cout << "Thank you! Have a nice day!." << endl;
}
return 0;
}
In this loop:
while (money < total) {
you are not modifying money or total so the loop will never exit.
You probably want to update money like this:
while (money < total) {
// ...
cin >> payment;
money += payment;
}
I'm making a simple c++ atm program, but I'm having trouble with getting the balance to change after I make a deposit or withdraw.
// C++ ATM
#include "std_lib_facilities.h"
int main()
{
bool card_is_inserted = false;
double balance = 0.0;
//double new_balance = balance;
// HOME
//Starts over if variable is false
while (card_is_inserted == false)
{
cout << "Wellcome to Well's Fargo ATM " << '\n'
<< "Insert card Yes or No"<< endl;
string request;
getline(cin,request);
// Function is needed for aceppting different no's and yes's
//-=-=-=--=-==--=-=-==-==-=--==--=-=-
// loads atm
if (request == "yes")
{
cout << "Alright, Your current balance is:" << endl
<< balance << endl;
card_is_inserted = true;
}
// home
string option = "cancel";
while (card_is_inserted == true)
{
cout << "Would you like to withdraw or deposit? (Cancel)"<< endl;
getline(cin,option);
double cash_ = 0;
if (option == "deposit")
{
cout << "How much money would you like to deposit?" << endl;
cin >> cash_;
double new_deposit_balance = balance + cash_;
cout << "You placed: $" << cash_ << endl
<< "Your New Balance is: $" << new_deposit_balance << endl;
}
if (option == "withdraw")
{
cout << "How much money would you like to withdraw?" << endl;
cin >> cash_;
double new_witdraw_balance = balance - cash_;
if(balance <= 0)
{
cout << "You don't have: $" << cash_ << endl;
}
else
{
cout << "You toke: $" << cash_ << endl
<< "Your New Balance is: $"<< new_witdraw_balance << endl;
}
}
if (option == "cancel")
{
cout << "Ok, bye" << endl;
card_is_inserted = false;
}
}
}
}
example: I type yes to make a deposit(or withdraw) and then place a simple double like 12.50 then it shows me my current balance which will be 12.50; afterward I want to make a withdraw of 12.00 with .50 left. But I cant because the balance variable didn't store my previous value which was 12.50. I tried making "double new_balance = balance" but doesn't work like in swift.
You are not setting balance to new_witdraw_balance or new_deposit_balance.
double new_deposit_balance = balance + cash_; doesn't set the balance value because you are bring in the value of balance, but you are not assigning the outcome of balance + cash_ to balance.
You need to put something like balance = new_witdraw_balance; and balance = new_deposit_balance; at the end of each if after cout statement.
if(option == "deposit")
{
cout << "How much money would you like to deposit?" << endl;
cin >> cash_;
double new_deposit_balance = balance + cash_;
cout << "You placed: $" << cash_ << endl << "Your New Balance is: $" << new_deposit_balance << endl;
balance = new_deposit_balance; // this
}
if(option == "withdraw")
{
cout << "How much money would you like to withdraw?" << endl;
cin >> cash_;
double new_witdraw_balance = balance - cash_;
if(balance <= 0)
{
cout << "You don't have: $" << cash_ << endl;
}
else
{
cout << "You toke: $" << cash_ << endl << "Your New Balance is: $"<< new_witdraw_balance << endl;
balance = new_witdraw_balance; // and this
}
}
The line double new_deposit_balance = balance + cash_; only assigns the new balance to new_deposit_balance, but then you don't do anything with that variable (except print the value). If you want the new balance to persist, you actually need to modify balance, not new_deposit_balance, so something like balance = balance + cash_; or balance += cash_;.
The variable double new_deposit_balance only exists in the if-block it's defined in, so once you leave the if-block, you lose the information in new_deposit_balance. On the other hand, since balance is defined outside your if-blocks and while-loops, its value will persist throughout your ATM operations.
Of course, you'd also need to apply the same fix to new_witdraw_balance.
I'm new here. Sorry if I'm not posting correctly. My program is comparing cell phone plans based on minutes. I want to know how I can compare plans to determine the best plan for the money. I believe I should be using minimum functions for this, but I'm honestly stuck. My code is below. Is it possible to find the minimum value from 3 separate functions? I'm not looking for an answer, but maybe an example or an article how to do so. Thanks!
#include<iostream>
using namespace std;
void companyA();
void companyB();
void CompanyC();
int min(); // I want to use this to find my minimum
int numEmployees;
int avgMin;
double totalCost;
// double bestChoice; Not used yet
int main()
{
double newMin;
cout << "Please enter number of employees." << endl;
cin >> numEmployees;
cout << "Please enter average minutes used by each employee. " << endl;
cin >> avgMin;
if (numEmployees < 0)
{
cout << "Incorrect value. Please enter positive number of employees." << endl;
cin >> numEmployees;
}
else if (avgMin < 0)
{
cout << "Incorrect value. Please enter positive number of minutes. " << endl;
cin >> avgMin;
}
cout << "\nStandard Packages" << endl;
cout << "Company A: For $29.99 per month, 450 minutes are included. Additional minutes are $0.35 per minute." << endl;
cout << "Company B: For $49.99 per month, 900 minutes are provided. Additional minutes are $0.30 per minute." << endl;
cout << "Company C: For $59.99 per month, unlimited minutes are provided." << endl;
companyA();
companyB();
companyC();
cout << "\nBased on the number of employees and average minutes used, " << x << "is the best choice." << endl;
system("pause");
return 0;
}
void companyA()
{
if (avgMin <= 450)
{
totalCost = 29.99*numEmployees;
cout << "\nCompany A will cost an $" << totalCost << " a month for " << numEmployees << " employee(s)." << endl;
}
else if (avgMin > 450)
{
totalCost = (avgMin-450)*0.35+29.99;
cout << "\nCompany A will cost an $" << totalCost << " a month for " << numEmployees << " employee(s)." << endl;
}
}
void companyB()
{
if (avgMin <= 900)
{
totalCost = 49.99*numEmployees;
cout << "Company B will cost an $" << totalCost << " a month for " << numEmployees << " employee(s)." << endl;
}
else if (avgMin > 900)
{
totalCost = (avgMin - 900)*0.30 + 49.99;
cout << "Company B will cost an $" << totalCost << " a month for " << numEmployees << " employee(s)." << endl;
}
}
void companyC()
{
totalCost = 59.99*numEmployees;
cout << "Company C will cost an $" << totalCost << " a month for " << numEmployees << " employee(s)." << endl;
}
I don't know if this is what you're looking for.
void minimum(double numEmployees, double avgMin);
double minimumCompany(double x, double y, double z);
void minimum(double numEmployees, double avgMin)
{
double totalCostA, totalCostB, totalCostC, minimumTotal;
string choice;
if (avgMin <= 450)
{
totalCostA = 29.99 * numEmployees;
cout << "\nCompany A will cost an $" << totalCostA << " a month for " << numEmployees << " employee(s)." << endl;
}
else if (avgMin > 450)
{
totalCostA = (avgMin - 450) * 0.35 + 29.99;
cout << "\nCompany A will cost an $" << totalCostA << " a month for " << numEmployees << " employee(s)." << endl;
}
if (avgMin <= 900)
{
totalCostB = 49.99*numEmployees;
cout << "Company B will cost an $" << totalCostB << " a month for " << numEmployees << " employee(s)." << endl;
}
else if (avgMin > 900)
{
totalCostB = (avgMin - 900)*0.30 + 49.99;
cout << "Company B will cost an $" << totalCostB << " a month for " << numEmployees << " employee(s)." << endl;
}
totalCostC = 59.99*numEmployees;
cout << "Company C will cost an $" << totalCostC << " a month for " << numEmployees << " employee(s)." << endl;
minimumTotal = minimumCompany(totalCostA, totalCostB, totalCostC);
if (minimumTotal == totalCostA)
{
choice = "Company A";
}
else if (minimumTotal == totalCostB)
{
choice = "Company B";
}
else
{
choice = "Company C";
}
cout << "\nBased on the number of employees and average minutes used, " << choice << " is the best choice." << endl;
}
double minimumCompany(double x, double y, double z)
{
double minimum = x;
if (y < minimum ) {
minimum = y;
}
if (z < minimum) {
minimum = z;
}
return minimum;
}
int main()
{
double numEmps, averageMin;
bool isValid = true;
while (isValid)
{
cout << "Please enter number of employees." << endl;
cin >> numEmps;
cout << "Please enter average minutes used by each employee. " << endl;
cin >> averageMin;
if ((numEmps < 0))
{
cout << "Please enter number of employees. " << endl;
cin >> numEmps;
isValid = true;
}
else
{
isValid = false;
}
if ((averageMin < 0))
{
cout << "Please enter average minutes used by each employee. " << endl;
cin >> numEmps;
isValid = true;
}
else
{
isValid = false;
}
}
cout << "\nStandard Packages" << endl;
cout << "Company A: For $29.99 per month, 450 minutes are included. Additional minutes are $0.35 per minute." << endl;
cout << "Company B: For $49.99 per month, 900 minutes are provided. Additional minutes are $0.30 per minute." << endl;
cout << "Company C: For $59.99 per month, unlimited minutes are provided." << endl;
minimum(numEmps, averageMin);
system("pause");
return 0;
}
Getting an unassigned variable error after the GetTransfer portion of the code. It is claiming account1 is the unassigned variable but from what i can see i have declared it. i have tried multiple times to correct it and i just can figure it out.
#include <iostream>
#include <conio.h>
using namespace std;
// Chance Pinkerton
// December 3, 2013
// CaseProject2Chapter3
struct bankInfo
{
int accountNum;
double startBal;
double endBal;
};
int main()
{
bankInfo account1;
bankInfo account2;
double transferAmt;
int GetAccount1();
int GetAccount2();
double GetBal1();
double GetBal2();
double GetTransfer();
account1.accountNum = GetAccount1();
while (account1.accountNum < 1000 || account1.accountNum > 9999)
{
cout << "Error. That account does not exsist." << endl;
account1.accountNum = GetAccount1();
}
GetBal1();
account2.accountNum = GetAccount2();
while (account2.accountNum < 1000 || account2.accountNum > 9999)
{
cout << "Error. That account number doesnt exsist." << endl;
account2.accountNum = GetAccount2();
}
if (account2.accountNum == account1.accountNum)
{
cout << "Error. Account numbers can not be the same " << endl;
account2.accountNum = GetAccount2();
}
GetBal2();
transferAmt = GetTransfer();
account1.accountNum = (account1.accountNum % 5) + (account1.accountNum * 10);
account2.accountNum = (account2.accountNum % 5) + (account2.accountNum * 10);
account1.endBal;
account2.endBal;
while (account1.endBal < 0)
{
cout << "Error. Account balance can not be negative." << endl;
GetTransfer();
if (account1.endBal < 10)
{
cout << "Warning. Account balance will be below $10.00 " << endl;
}
}
account1.endBal = account1.startBal - transferAmt;
account2.endBal = account2.startBal + transferAmt;
cout << "Account number 1: " << account1.accountNum << endl;
cout << "Starting balance: " << account1.startBal << endl;
cout << "Ending balance: " << account1.endBal << endl;
cout << "Account number 2: " << account2.accountNum << endl;
cout << "Starting balance: " << account2.startBal << endl;
cout << "Ending balance: " << account2.endBal << endl;
getch();
return 0;
}
int GetAccount1()
{
int accountNum;
cout << "Please enter your account number " << endl;
cin >> accountNum;
return accountNum;
}
int GetAccount2()
{
int accountNum;
cout << "Please enter the second account number " << endl;
cin >> accountNum;
return accountNum;
}
double GetBal1()
{
double startBal;
cout << "Enter your account balance " << endl;
cin >> startBal;
return startBal;
}
double GetBal2()
{
double startBal;
cout << "Enter the second account balance " << endl;
cin >> startBal;
return startBal;
}
double GetTransfer()
{
double transferAmt;
cout << "How much would you like to transfer to the second account " << endl;
cin >> transferAmt;
return transferAmt;
}
These two statements do exactly nothing, and are likely the source of the warning the compiler is giving you:
account1.endBal;
account2.endBal;
Furthermore, I think you need to actually capture the return value of GetTransfer() here, perhaps into transferAmt:
GetTransfer();
You probably need to rethink this entire while loop, especially taking into account how transferAmt relates to account1.endBal:
while (account1.endBal < 0)
{
cout << "Error. Account balance can not be negative." << endl;
GetTransfer();
if (account1.endBal < 10)
{
cout << "Warning. Account balance will be below $10.00 " << endl;
}
}
For example, you don't want to update endBal until you know the transfer will succeed. Furthermore, your low-balance warning is in completely the wrong place.