我对编码非常陌生,并且遇到了 if-else 程序的奇怪障碍。我的代码中有很多注释来解释发生了什么,所以我只发布代码,但基本问题是当我尝试简化嵌套语句时,我只执行了一个条件(覆盖所有其他条件)。例如,如果我想在“x = 4”时发生某些事情,那么只有那个条件会被执行——即使它是错误的!但是,如果我将其声明为“x < 5 && x > 3”,那么程序可以正常工作(针对真假条件的适当执行),但这似乎很混乱——尤其是因为我想要对多个输入做出某些响应。
我搜索了该站点并找不到这个特定问题,并且“类似问题”似乎也不适用。所以知道发生了什么吗?有没有什么东西可以使程序只执行一个 if-else 语句而忽略所有其他语句,即使该语句是错误的?
代码:问题在于末尾附近的两个 elseif 语句(标有注释)。
#include <iostream>
using namespace std;
int main()
{//This a program using loop functions to have the user
//guess variable "guess" (which we'll make "5"), until the user gets it
//right, and provides hints to help the user out
cout<<"Can you guess the number I'm thinking? It's between 1 and 10.\n";
//Prompts the user to input a guess
int guess;
//Declares the variable that the user will input
cin>>guess;
//Before the loop begins, the user input a guess
cout<<"\n";
//This gives us a line break after the answer is submitted
while (guess != 5){//Guessing incorrectly starts the loop
//The program is going to keep asking the user to guess
//until the user guesses "5"
if (guess < 1 ){//The program will warn the user if they're out of range, here it's too low
cout<<"No, that's too low! Guess a number between 1 and 10.\n";
cin>>guess; //Allow the user to guess again
cout<<"\n"; //Add a line break after the input
}
else //Now, give responses for other conditions
if(guess > 10){//Warn the user if they guess too high
cout<<"Too high! Guess a number between 1 and 10.\n";
cin>>guess;
cout<<"\n";
}
else //Tell the user if they're getting close.
//Not sure why I can't simply say if "guess = 4,6"
//Doing so causes only this response to execute, ignoring
//the others, except the above ">" and "<" statements
//which is why I'm continung to use </> statements here
if(guess > 5 && guess < 7 || guess < 5 && guess > 3){
cout<<"VERY close! Keep trying.\n";
cin>>guess;
cout<<"\n";
}
else //Tell the user if they're sort of close
//Again, not sure why I can't just say "guess=3,7"
if(guess > 2 && guess < 4 || guess > 6 && guess < 8){
cout<<"Close, but no cigar. Try again.\n";
cin>>guess;
cout<<"\n";
}
else {//For all other responses, we output this
cout<<"Guess again.\n";
cin>>guess;
cout<<endl; //We need to end the loop here, as these are all the conditions
//This kept creating a line break. My assumption is that
//by virtue of ending the loop, a line break was created
}
}
if(guess = 5){//Outside the loop, we need to specify the correct answer
//because the loop is only working while the answer in incorrect
cout<<"Good job. "<<guess<<" is right!\n";
}
cin.get();//This keeps the program from closing after completion
}
//Done