I am writing a "vending machine" code for c++ 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. Can someone help me with my error?
Edit: the code works after I added float cost = 0; to my code. However, there is an error with the logic of calculating the payment. For example, when I buy a $3 item and pay with $1, I get a $1 change. Can anyone help me with that?
Thanks in advanced!
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;
float cost = 0;
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;
}
Aucun commentaire:
Enregistrer un commentaire