2013-06-01 99 views
0

我想用在C#用戶輸入來實現歐幾里德算法片斷作爲我學習這門語言的過程的一部分。 MVS告訴我,if和elif語句以及這些語句的尾括號存在錯誤。現在,從pythonic背景來看,這對我來說似乎很自然,所以請幫助我確定可能的錯誤。非常感謝幫助。錯誤在C#中使用if語句

代碼:

namespace EuclideanAlgorithm 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Console.WriteLine("Enter two numbers to calculate their GCD"); 

      int input1 = Convert.ToInt32(Console.ReadLine()); 
      int input2 = Convert.ToInt32(Console.ReadLine()); 
      int remainder; 
      int a; 
      int b; 

      if (input1 == input2); 
      { 
       Console.Write("The GCD of", input1, "and", input2, "is", input1); 
       Console.ReadLine(); 
      } 
      else if (input1 > input2); 
      { 
       a = input1; 
       b = input2; 

       while (remainder != 0); 
       { 
        remainder = a % b; 
        a = b; 
        b = remainder; 
       } 
       Console.Write("The GCD of", input1, "and", input2, "is", b); 
       Console.ReadLine(); 
      } 
      else if (input1 < input2); 
      { 
       a = input2; 
       b = input1; 

       while (remainder != 0); 
       { 
        remainder = a % b; 
        a = b; 
        b = remainder; 
       } 

       Console.WriteLine("The GCD of", input1, "and", input2, "is", b); 
       Console.ReadLine(); 
      } 
     } 
    } 
} 

回答

7

那麼你需要刪除的if S中的分號。 所以:

if (input1 == input2); 

變爲:

if (input1 == input2) 

這也無二else ifwhile。 還只是一個側面說明:

Console.Write("The GCD of", input1, "and", input2, "is", input1); 

這將產生:

如果你想要做你需要做這樣一個string.Format的GCD:

Console.Write("The GCD of {0} and {1} is {2}", input1, input2, input1); 

Here的更多信息在string.Format

1件事 - 確保你初始化後餘你設置它,否則你將無法編譯局部變量剩餘訪問之前可能無法初始化:

int remainder = 0; 

我希望這有助於。

編輯

如果你希望你的其餘部分是0以外的任何東西你第一次評估它,你可以改用一個do/while循環:

do 
{ 
    remainder = a % b; 
    a = b; 
    b = remainder; 

} while (remainder != 0); 
+1

這真的很有幫助...謝謝!在旁註中,我想知道爲什麼while語句不會在餘數被賦值爲0但是循環結束後立即結束。提前致謝。 –

+0

@SebastianGarrido因爲你需要在評估它之前計算它,所以我希望我有道理。基本上再計算一次*在* while - >'remaining = a%b;'之前,讓它進入一段時間。 –

+0

有什麼辦法可以繞過這種行爲嗎? –

0

你有半冒號這些if語句

if (input1 == input2);

else if (input1 < input2);

當有上有半冒號它不進入括號,改變他們

if (input1 == input2)

else if (input1 < input2)

既然你已經YOUT {那裏,我們不需要添加他們再次,

現在它應該工作

同爲while循環在以P,這是我剛纔看到

+0

我想知道爲什麼在使用中的分號,現在感謝你我有一些直覺,謝謝。 –

0

下面的線接錯:

if (input1 == input2); 
[...] 
else if (input1 > input2); 
[...] 
while (remainder != 0); 
[...] 
else if (input1 < input2); 
[...] 
while (remainder != 0); 

在這些的結束分號(;)結束髮言,後不正確使括號({) 。

待辦事項結束ifwhilefor語句用分號。