制作一个允许用户输入输入的程序,以便他们可以获得简单数学科目的帮助。我以为我已经成功了,如果他们进入了一个不在那里的主题,那么就会说(不)见下面的其他声明。知道为什么当我运行它时,它仍然包含输入主题正确时的else语句? http://prntscr.com/ey3qyh
search = "triangle";
pos = sentence.find(search);
if (pos != string::npos)
// source http://www.mathopenref.com/triangle.html
cout << "A closed figure consisting of three line segments linked end-to-end. A 3 - sided polygon." << endl;
search = "square";
pos = sentence.find(search);
if (pos != string::npos)
// source http://www.mathopenref.com/square.html
cout << "A 4-sided regular polygon with all sides equal and all internal angles 90°" << endl;
else
cout << "Sorry, it seems I have no information on this topic." << endl;
case 2:
break;
default:
cout << "Invalid input" << endl;
}
答案 0 :(得分:2)
这是您的计划所做的事情:
因为&#34;三角形&#34;找到了&#34; square&#34;没有找到,它打印出三角形的定义和道歉。换句话说,计算机正在完全按照你的要求去做 - 问题是什么?
答案 1 :(得分:0)
您至少有两个选择:
嵌套选项,以便仅在前一个选项不起作用时评估每个后续选项:
search = "triangle";
pos = sentence.find(search);
if (pos != string::npos){
// link to info about triangle
cout << "...info about triangle..." << endl;
}else{
search = "square";
pos = sentence.find(search);
if (pos != string::npos){
// link to info about square
cout << "...info about square..." << endl;
}else{
search = "pentagon";
pos = sentence.find(search);
if (pos != string::npos){
// link to info about pentagon
cout << "...info about pentagon..." << endl;
}else{
cout << "Sorry, it seems I have no information on this topic." << endl;
}
}
}
或者,如果您可以将if条件的所有代码放入if语句中,则可以使用if语句:
if (sentence.find("triangle") != string::npos){
// link to info about triangle
cout << "...info about triangle..." << endl;
}else if (sentence.find("square") != string::npos){
// link to info about square
cout << "...info about square..." << endl;
}else if (sentence.find("pentagon") != string::npos){
// link to info about pentagon
cout << "...info about pentagon..." << endl;
}else{
cout << "Sorry, it seems I have no information on this topic." << endl;
}
您使用哪一个取决于您是否可以将if条件的所有代码都放入条件本身。