2015-08-16 112 views
-1

開始:我的代碼有什麼問題?

 int UserInput1; 
     int UserInput2; 
     int UserInput3; 

     Console.WriteLine("Input the first number: "); 
     UserInput1 = Convert.ToInt32(Console.ReadLine()); 

     Console.ReadKey(); 
     Console.WriteLine(); 

     Console.WriteLine("Input the second number: "); 
     UserInput2 = Convert.ToInt32(Console.ReadLine()); 

     Console.ReadKey(); 
     Console.WriteLine(); 

     Console.WriteLine("What is " + UserInput1 + " divided by " + UserInput2 + "?"); 
     UserInput3 = Convert.ToInt32(Console.ReadLine()); 

     Console.ReadKey(); 
     Console.WriteLine(); 

     int Answer = UserInput1/UserInput2; 

     if (Answer != UserInput3) 
     { 

      Console.WriteLine("Wrong answer, try again. "); 

      goto Start; 


     } 
     else if (Answer == UserInput3) 
     { 

      Console.WriteLine("Congratulation, your are correct. The correct answer, as you've \nstated is " + UserInput3); 

     } 

這工作。但是,當我用「else」替換「else if」時,會彈出一個錯誤消息,說在「(Answer == UserInput3)」後面會出現分號。「

這是一個錯誤還是我沒有看到一個簡單的錯誤?

感謝您的閱讀。

+1

在C#中沒有語法可以讓你在'else'之後指定一個附加條件。當然排除中間的法律無論如何都不需要。 – dasblinkenlight

回答

1

您要更換...

if (...) { 
    ... 
} else if (...) { 
    ... 
} 

if (...) { 
    ... 
} else (...) { 
    ... 
} 

後者不是有效的構造:else並不需要的條件。您需要if

+0

哦。對。由於答案必須等於UserInput3或不等於UserInput3。我懂了。謝謝。 :] – Ken

+0

不,它與邏輯錯誤無關,只是一個句法:你可以有其他的''(沒有第二個條件)或者'else else if(...){'(with one)。在這種情況下,你可以使用'} else {'。 – Tordek

1

這是因爲「else」語句沒有采用條件,並且如果if語句爲假,它會自動運行。 Shoulde是:

if (Answer != UserInput3) 
    { 

     Console.WriteLine("Wrong answer, try again. "); 

     goto Start; 


    } 
    else 
    { 

     Console.WriteLine("Congratulation, your are correct. The correct answer, as you've \nstated is " + UserInput3); 

    } 
+0

感謝您的評論。 :] – Ken