目前我正在尝试编写自动售货机程序,而我似乎有两个逻辑错误,我无法弄清楚。首先,当我尝试为我的自动售货机程序选择不同的产品时,它总是选择第一个产品而我不知道为什么。其次,我试图让退出条件允许用户随时退出程序,但程序总是在我询问用户后无论如何都会结束。以下是我的代码:
//Vending Machine Program
#include <iostream>;
using namespace std;
int main()
{
double product1 = 59.99;
double product2 = 59.99;
double product3 = 59.99;
double product4 = 59.99;
double customerMoney = 0.00;
cout << "How much money do you have? ";
cin >> customerMoney;
while (customerMoney >= 59.99)
{
int customerChoice = 0;
//bool exitProgram;
cout << "Which product would you like to buy?\n Enter '1' for Killzone: Shadow Fall ($59.99)\n Enter '2' for Deadrising 3 ($59.99)\n Enter '3' for Call of Duty Ghosts ($59.99)\n Enter '4' for Madden NFL 25 ($59.99)";
cin >> customerChoice;
if (customerChoice = 1)
{
cout << "You have selected Killzone: Shadow Fall\n";
customerMoney = customerMoney - product1;
cout << "You have $" << customerMoney << " left\n";
/*cout << "Would you like to exit the program? (Enter '1' for true and '0' for false)";
cin >> exitProgram;
if (exitProgram = 1)
{
return 0;
}*/
}
else if (customerChoice = 2)
{
cout << "You have selected Deadrising 3\n";
customerMoney = customerMoney - product2;
cout << "You have $" << customerMoney << " left\n";
/*cout << "Would you like to exit the program? (Enter '1' for true and '0' for false)";
cin >> exitProgram;
if (exitProgram = 1)
{
return 0;
}*/
}
else if (customerChoice = 3)
{
cout << "You have selected Call of Duty Ghosts\n";
customerMoney = customerMoney - product3;
cout << "You have $" << customerMoney << " left\n";
/*cout << "Would you like to exit the program? (Enter '1' for true and '0' for false)";
cin >> exitProgram;
if (exitProgram = 1)
{
return 0;
}*/
}
else if (customerChoice = 4)
{
cout << "You have selected Madden NFL 25\n";
customerMoney = customerMoney - product4;
cout << "You have $" << customerMoney << " left\n";
/*cout << "Would you like to exit the program? (Enter '1' for true and '0' for false)";
cin >> exitProgram;
if (exitProgram = 1)
{
return 0;
}*/
}
else
{
cout << "You don't have enough money to purchase anything else. Thank you for shopping!";
}
}
cin.get();
return 0;
}
答案 0 :(得分:5)
if (customerChoice = 1)
您正在使用“=”这是一个分配。你需要“==”
if (customerChoice == 1)
这不会引发编译错误的原因是从技术上讲,分配确实会返回一个值。事实上,在您的情况下,为customerChoice分配1的返回值将为1,这将在if语句中评估为True。