#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int number;
float cost;
char beverage;
bool validBeverage;
cout << fixed << showpoint << setprecision(2);
do
{
cout << endl << endl;
cout << "Hot Beverage Menu" << endl << endl;
cout << "A: Coffee $1.00" << endl;
cout << "B: Tea $ .75" << endl;
cout << "C: Hot Chocolate $1.25" << endl;
cout << "D: Cappuccino $2.50" << endl <<endl << endl;
cout << "Enter the beverage A,B,C, or D you desire" << endl;
cout << "Enter E to exit the program" << endl << endl;
cin>>beverage;
while(beverage!='A'||beverage!='B'||beverage!='C'||beverage!='D'||beverage!='E'||beverage!='a'||beverage!='b'||beverage!='c'||
beverage!='d'||beverage!='e')
{
cout<<"Your selection is invalid please re-enter ";
cin>>beverage;
}
switch(beverage)
{
case 'a': validBeverage = true;
case 'A': validBeverage = true;
case 'b': validBeverage = true;
case 'B': validBeverage = true;
case 'c': validBeverage = true;
case 'C': validBeverage = true;
case 'd': validBeverage = true;
case 'D': validBeverage = true;
break;
default: validBeverage = false;
}
if (validBeverage == true)
{
cout << "How many cups would you like?" << endl;
cin>>number;
}
// Fill in the code to begin a switch statement
switch(beverage)
{
case 'a': cost = number * 1.0;
case 'A': cost = number * 1.0;
cout << "The total cost is $ " << cost << endl;
break;
case 'b': cost = number * 0.75;
case 'B': cost = number * 0.75;
cout<< "The total cost is $ " << cost << endl;
break;
case 'c': cost = number * 1.25;
case 'C': cost = number * 1.25;
cout << "The total cost is $ " << cost << endl;
break;
case 'd': cost = number * 2.50;
case 'D': cost = number * 2.50;
cout << "The total cost is $ " << cost << endl;
case 'e': cout << " Please come again" << endl;
case 'E': cout << " Please come again" << endl;
break;
default:cout << " You have enter an invalid selection"<<endl;
cout << " Try again please" << endl;
}
}while(beverage!='e'||beverage!='E');
}
我试过运行这个程序,但它总是让我输入一个无效的选择。 我已经尝试修改while循环,但它不起作用;它是while循环吗? 另外还不确定我是否在do中正确写了while语句。
答案 0 :(得分:3)
以这种情况为例,同样的问题也存在于其他问题中。
while (beverage!='e'||beverage!='E');
字符不等于'e'
,或等于'e'
,在这种情况下它不等于'E'
,因此条件始终为真。
你想要的是合乎逻辑的。
答案 1 :(得分:1)
更改
while(beverage!='e'||beverage!='E'); // Condition becomes true always
到
while(beverage!='e'&& beverage!='E');
同样在第一个while循环条件表达式
中用||
替换所有&&
while(beverage!='A' && beverage!='B' &&beverage!='C'&& beverage!='D' && beverage!='E' && beverage!='a' && beverage!='b' && beverage!='c' &&
beverage!='d' && beverage!='e')