我试图在下面做出如下声明。 如果年龄大于20且小于50,继续。 如果年龄小于20且大于50,则重新启动错误。 如果有的话,错误,重启。
但是,出于某种原因,如果有条件,它会直接跳过其他地方并直接转向其他地方。如果我输入" 19"对于年龄,它输出"错误。",如果我输入51年龄,它输出"错误。"怎么了?
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int plyAgeCreate() {
int plyAge = 0;
cout << "Enter an age" << endl;
cin >> plyAge;
//If age is greator than 20 and less than 50, accept.
//Else if age is less than 20 but greator than 50, decline.
//else, error. Restart.
if (plyAge >= 20 && plyAge <= 50) {
cout << "Welcome!" << endl;
}
else if (plyAge < 20 && plyAge > 50) { //Why is this being skipped?
cout << "Between 20 and 50" << endl;
return plyAgeCreate();
}
else {
cout << "Error" << endl;
return plyAgeCreate();
}
}
int main()
{
plyAgeCreate();
system("pause");
return 0;
}
答案 0 :(得分:1)
错误的逻辑:
否则if(plyAge&lt; 20&amp;&amp; plyAge&gt; 50)//这种情况永远不会成真
应该是
else if (plyAge < 20 || plyAge > 50)
答案 1 :(得分:1)
使用或,而不是和。如果数字小于20且超过50,它只会进入那里,这是不可能的。如果是19,则必须更改为51,或者将其更改为此或删除它。
else if (plyAge < 20 || plyAge > 50) { //Why is this being skipped?
答案 2 :(得分:1)
试试这个。
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int plyAgeCreate() {
int plyAge = 0;
cout << "Enter an age" << endl;
cin >> plyAge;
//If age is greator than 20 and less than 50, accept.
//Else if age is less than 20 but greator than 50, decline.
//else, error. Restart.
if (plyAge >= 20 && plyAge <= 50) {
// This means Age is Between 20 and 50
}
else {
//This means age is below 20 OR above 50
}
// There cannot another case. Either between 20 - 50 or not between 20 - 50
}
int main()
{
plyAgeCreate();
system("pause");
return 0;
}