2012-11-14 42 views
0

我有當前的編碼,我覺得它接近我所需要的,但我似乎無法得到它爲我想要的工作。我試圖讓它輸出輸入的兩個數字的最高公因子。最高的公因子C#

  i = myInt; 

      { 
       if (myInt % i == 0 && myInt2 % i == 0) 
       { 
        Console.Write("Your GCF is..."); 
        Console.Write("{0} ", i); 
        Console.ReadLine(); 

       } 
       else 
        i--; 
       goto; 
      } 
+15

轉到?我想我只是在嘴裏吐了一下。 –

+1

這是功課嗎?第二次刪除goto! –

+0

那麼有什麼不工作?它是否會產生錯誤,你是否得到誤報,沒有答案,它是否永遠運行,是否給出了錯誤的答案,它只是有時工作,你是否真的沒有運行它,它不會編譯,[...]? – Servy

回答

-1
 { 
label: 
      if (myInt % i == 0 && myInt2 % i == 0) 
      { 
       Console.Write("Your GCF is..."); 
       Console.Write("{0} ", i); 
       Console.ReadLine(); 

      } 
      else 
       i--; 
      goto label; 
     } 

會做。但是,這是一個非常糟糕的主意。寧可學習如何使用while

+4

看起來你應該重構,擺脫那GOTO ... YUK ...! – MethodMan

+1

雖然這比OP的代碼更好,但這有點像說99999.99美元比10000美元更好。這是不值得指出的那種差異。 – Bobson

+2

爲什麼downvotes? Yossarian正在向OP展示如何改變代碼的工作方式,並告訴他最好使用'while'。 – comecme

0

正如其他人在評論中所說的那樣,您應該避免使用goto聲明,因爲它們是不好的練習,特別是在您正在學習大學編程課程時(通常應該符合結構編程)。相反,使用while循環(或任何其他)有兩個條件,如在示例中所示。另外,我認爲你應該從較小的數字開始搜索(第一次輸入不需要更小),這在性能方面略有改進。這是代碼:

static void Main(string[] args) 
{  
    string myInput; 
    int myInt; 
    string myInput2; 
    int myInt2; 
    int i; 

    Console.Write("Please enter a number: "); 
    myInput = Console.ReadLine(); 
    myInt = Int32.Parse(myInput); 

    Console.Write("Please enter another number: "); 
    myInput2 = Console.ReadLine(); 
    myInt2 = Int32.Parse(myInput2); 

    i = myInt > myInt2 ? myInt2 : myInt; 
    bool found = false; 
    while(!found && i>0) 
    { 
     if (myInt % i == 0 && myInt2 % i == 0) 
     { 
      Console.Write("Your GCF is..."); 
      Console.Write("{0} ", i); 
      Console.ReadLine(); 
      found = true; 
     } 
     else 
      i--; 
    } 
} 

編輯:我包括其他可能的解決方案由於@Servy

bool found = false; 
for(i = Math.Min(myInt, myInt2); !found && i>0; i--) 
{ 
    if (myInt % i == 0 && myInt2 % i == 0) 
    { 
     Console.Write("Your GCF is..."); 
     Console.Write("{0} ", i); 
     Console.ReadLine(); 
     found = true; 
    } 
} 
+0

我會把'{}'放在其他地方,但這是一種風格。沒有不同的功能,直到你不小心添加了一條應該在else和not中的新行。 – Bobson

+0

@Bobson好點,我總是這麼做,只是不想大幅改變OP的代碼。不過,我經常收到一些問題,比如「我只有一​​個聲明時需要括號嗎?」 –

+0

而不是'myInt> myInt2? myInt2:myInt;'我會用'Math.Max'。它使意圖更清楚。你也可以使用'for'循環而不是'while',因爲你在開始時創建了一個循環變量,並且每次都在一段時間內取而代之。再次,只是使意圖更清晰,而不是實際功能的任何變化。哦,並且不需要布爾型的「找到」。既然你只在循環的「結束」處將它設置爲true,你可以在'for' /'while'條件下有效地使'if'成爲表達式;它會清理代碼。 – Servy