我的节目中我做错了什么? [英] What am I doing wrong in my program?
问题描述
int main(int argc, char** argv)
{
string stopLightColor = "" ;
cout << "Please enter what your stoplight color is: " << endl ;
cin >> stopLightColor;
if (stopLightColor == "red" || "yellow") {
cout << "Please stop." << endl ;
}
else if (stopLightColor == "green")
{
cout << "Continue" << endl ;
}
return 0 ;
}
无论我输入什么,答案总是请停止。
我尝试了什么:
我没有尝试任何新的东西,因为我不喜欢知道我能解决的问题。
No matter what I type in, the answer always is "Please stop."
What I have tried:
I haven't necessarily tried anything new because I don't know what I could fix about it.
推荐答案
什么是我在程序中做错了吗?
What am I doing wrong in my program?
因为你不知道C ++语法。
通过阅读文档和跟随tutos来学习C ++。
特别注意逻辑运算符。
Because you don't know the C++ syntax.
Learn really C++ by reading documentation and follow tutos.
Pay particular attention to logical operators.
正如其他人已经建议你误解了条件表达式在C ++中是如何工作的。也就是说,我想有办法改进你的代码。我想有两种情况:
(1)您信任信号量(用户输入)到是'红色'或'黄色'或'绿色'。
在这种情况下,代码可以简单写一下
As others already suggested you misunderstood how conditional expressions works in C++. That said, I suppose there ways to improve your code. I suppose there are two scenarios:
(1) You trust the semaphore (the user input) to be either 'red' or 'yellow' or 'green'.
In such scenario, the code could be written simply
if (stopLightColor == "green")
{
cout << "Continue" << endl;
}
else // it IS either 'red' or 'yellow', don't bother to check
{
cout << "Please stop" << endl;
}
(2)您允许信号量(用户输入)有时会被打破。
在这种情况下你必须处理'破碎的'可能性。
(2) You allow the semaphore (the user input) to be broken, at times.
In such a scenario you HAVE to handle the 'broken' eventuality.
if (stopLightColor == "green")
{
cout << "Continue" << endl;
}
else if ( stopLightColor == "yellow" || stopLightColor == "red")
{
cout << "Please stop" << endl;
}
else // the semaphore is broken
{
cout << "Warning: the semaphore is broken, please go on very carefully" << endl;
}
正如ppolymorphe建议的那样,看看这一行
As ppolymorphe has suggested, look at this line
if (stopLightColor == "red" || "yellow")
你能想到它的正确方法吗?写的?
can you think of the correct way it should be written ?
这篇关于我的节目中我做错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!