저는 코딩하기가 매우 쉽고 if-else 프로그램으로 이상한로드 블록을 실행했습니다. 내 코드에는 많은 일들이 설명되어 있으므로 코드를 게시 할 것입니다. 그러나 기본적인 문제는 중첩 된 문을 단순화하려고 할 때 한 조건 만 실행된다는 것입니다 (모든 다른 조건을 무시합니다.). 예를 들어, "x = 4"일 때 무언가를 원한다면, 그 조건 만 실행됩니다 - 거짓 일지라도! 그러나 "x & x> 3"으로 표시하면 프로그램이 정상적으로 작동하고 (사실과 잘못된 조건이 적절하게 실행 됨) 지저분 해 보입니다. 특히 여러 입력에 대한 특정 응답을 원하므로 특히 그렇습니다.하나의 조건 만 실행하는 중첩 된 if-else 문 (C++)
사이트를 검색 한 결과이 특정 문제를 찾을 수 없었으며 "Similar Questions"는 적용되지 않는 것으로 보입니다. 무슨 생각 이니? 프로그램이 하나의 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
'='과'=='의 차이점을 찾으십시오. – Beta
경고 수준을 올리면 컴파일러에서 실제로 도움이되는 말을해야합니다. – chris
""x = 4 "일 때 어떤 일이 일어나기를 원하면 그 조건 만 실행됩니다."'x = 4'는'x'에 값 4를 할당하고, 이전 값을 덮어 쓰고, 부울 의미에서'true'인지 검사합니다. 항상 영이 아닌 숫자는'true'로 간주됩니다. 조건은'x == 4'이어야합니다. –