2013-05-30 4 views
0

저는 코딩하기가 매우 쉽고 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 
+1

'='과'=='의 차이점을 찾으십시오. – Beta

+1

경고 수준을 올리면 컴파일러에서 실제로 도움이되는 말을해야합니다. – chris

+0

""x = 4 "일 때 어떤 일이 일어나기를 원하면 그 조건 만 실행됩니다."'x = 4'는'x'에 값 4를 할당하고, 이전 값을 덮어 쓰고, 부울 의미에서'true'인지 검사합니다. 항상 영이 아닌 숫자는'true'로 간주됩니다. 조건은'x == 4'이어야합니다. –

답변

1

한 점은 다음과 같습니다

if(guess = 5){ 

당신은 정말 logical comparison하지 assignment을 의미

if(guess == 5){ 

을해야합니다.

다른 점 C++ Operator Precedence에 따른 &&||가보다 높은 우선 순위를 갖는다는 것이다. 최소한, 따라서

(guess == 6 || guess == 4) 

if((guess > 2 && guess < 4) || (guess > 6 && guess < 8)) 
+0

흠 .. 이전에 "=="을 사용해 보았는데 작동하지 않았지만 지금은 작동하는 것 같습니다. 시도하기 전에 여러 가지 다른 오류가 있었기 때문에 당시로서는 도움이되지 않았습니다. 감사! 지금 일하고있어. –

+0

@ D.Lowe 환영합니다. – taocp

0

이야기 정수,

(guess > 5 && guess < 7 || guess < 5 && guess > 3) 

은 동일합니다 : 당신은 명확하게 논리를 표현하는 논리 조건에 ()을 사용해야합니다. 다음과 같이 재구성 :

while (guess != 5) { 
    if (guess < 1) { 
    } 
    else if (guess > 10) 
    } 
    else if (guess == 6 || guess == 4) { 
    } 
    else if (guess == 3 || guess == 7) { 
    } 
    else { // executes for 1, 2, 5 (then leaves loop), 8, 9, 10 
    } 
} 

은 또한 말은 ...

C++에서
if (guess = 5) // assignment and "if" becomes true (always) 
0

if (guess == 5) // equivalence check 

하지, if(x = whatever) 물어 구문 잘못이 아니다. 그러나 그것은 당신이 생각하는 것을하지 않습니다.

//is the value of x equal to 4? 
if(x == 4) 

//does the assignment of 4 to the variable x return true? (meaning it worked)` 
if(x = 4) 

그래서 당신이 생각하는 것은 잘못된 것을 무엇 일어나고있는 사실은 사실이다 :

여기의 차이입니다.