我正在尝试在 C++ 中创建一个复杂的 if 语句,这将使我免于编写一大堆 if 语句,我想知道下面的代码是否确实有意义,或者我忽略了一个错误。
if(input==choice) {
cout << "Tie!" << endl;
}else if(input=="rock" && choice=="scissors"
|| input=="scissors" && choice=="paper"
|| input="paper" && choice=="rock") {
cout << input " beats " << choice << ", you win!" << endl;
}else if(input=="rock" && choice=="paper"
|| input=="scissors" && choice=="rock"
|| input=="paper" && choice=="scissors"){
cout << choice << " beats " << input << ", you lose!" << endl;
}
我想要实现的是:
"if input is x AND choice is y, OR if...."
基本上,我正在测试多个“if-and”条件,以便在满足任何 if-and 条件时执行一行代码。输出抛出“不匹配‘operator||’”错误。
你有一个错字input="paper" && choice=="rock")
,但我建议您修复代码,而不是修复拼写错误。难怪你在这个巨大的条件块中犯了一个拼写错误。你有很多重复和混合逻辑与输出。如果您在包含上花费了一些行,那么您可以在代码上节省一些...
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <algorithm>
bool win(const std::string& input, const std::string& choice) {
static const std::vector<std::pair<std::string, std::string>> wins =
{ { "rock", "scissors" },
{ "scissors", "paper" },
{ "paper", "rock" }
};
return std::find(wins.begin(), wins.end(), std::make_pair(input, choice))
!= wins.end();
}
int main() {
std::string choice = "paper";
std::string input = "scissors";
if (win(choice, input)) { std::cout << "you win! \n"; }
else { std::cout << "you lose! \n"; }
}
下一步,您应该消除所有这些字符串,例如通过使用评论中讨论的枚举。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)