我有一份上学的任务,非常简单,只是从一个联合中心订购汉堡并计算成本。我已经尝试使用if语句来确保用户喜欢他们的订单,但它一直给我和错误,无论我的变量" yesorno"是字符串或字符。
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
int main() {
char yesorno;
int burgers, fries, drinks;
int i=0;
while (i=0) {
cout<<"Aidan: 'Welcome to the Christopher Burger Joint!\nOur burgers are $4.00, fries are $2.50, and drinks are $1.50.";
cout<<"\nHow many burgers will you be having today?";
cin>>burgers;
cout<<"\nHow many fries will you be having today?";
cin>>fries;
cout<<"\nand how many drinks for you today?";
cin>>drinks;
cout<<"\nSo here is your current order:\nBurgers: "<<burgers<<"\nFries: "<<fries<<"\nDrinks: "<<drinks;
cout<<"Is this all?\nYes or No: ";
cin>>yesorno;
if (yesorno = "yes") {
i=2;
}
}
int grosstotal = (burgers*4)+(fries*2.5)+(drinks*1.5);
int tax = grosstotal*.12;
int total = tax+grosstotal;
cout<<"\nYour total before tax is $"<<grosstotal<<",\nYour tax is $"<<tax<<",\nAnd your total today is $"<<total<<".\nEnjoy!'";
return 0;
}
答案 0 :(得分:2)
对于初学者来说,在while语句中有赋值而不是比较
while (i=0) {
^^^
在此if语句中
if (yesorno = "yes") {
^^^
再次分配而不是比较。
要从用户接受类似"yes"
的字符串,变量yesorno
应声明为类型为std::string
。
而不是while
循环,最好使用do-while
循环。例如
int main() {
string yesorno;
int burgers, fries, drinks;
do {
//...
cin>>yesorno;
} while ( yesorno != "yes" );
此外,您可以删除标头<cstdlib>
,因为标头中的声明都未在程序中使用。
答案 1 :(得分:1)
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
int main() {
string yesorno;
int burgers, fries, drinks;
int i=0;
while (i==0) {
cout<<"Aidan: 'Welcome to the Christopher Burger Joint!\nOur burgers are $4.00, fries are $2.50, and drinks are $1.50.";
cout<<"\nHow many burgers will you be having today?";
cin>>burgers;
cout<<"\nHow many fries will you be having today?";
cin>>fries;
cout<<"\nand how many drinks for you today?";
cin>>drinks;
cout<<"\nSo here is your current order:\nBurgers: "<<burgers<<"\nFries: "<<fries<<"\nDrinks: "<<drinks;
cout<<"Is this all?\nYes or No: ";
cin>>yesorno;
if (yesorno == "yes") {
i=2;
}
}
int grosstotal = (burgers*4)+(fries*2.5)+(drinks*1.5);
int tax = grosstotal*.12;
int total = tax+grosstotal;
cout<<"\nYour total before tax is $"<<grosstotal<<",\nYour tax is $"<<tax<<",\nAnd your total today is $"<<total<<".\nEnjoy!'";
return 0;
}
这对我有用。你错过了几个==
。
答案 2 :(得分:1)
实际上你正在为变量yesorno分配字符串yes,你在那里做错了=是一个用于比较的赋值运算符==用于比较所以insted
if (yesorno = "yes") {
i=2;
}
写
if (yesorno == "yes") {
i=2;
}