正如其他人在評論中所說的那樣,您應該避免使用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;
}
}
轉到?我想我只是在嘴裏吐了一下。 –
這是功課嗎?第二次刪除goto! –
那麼有什麼不工作?它是否會產生錯誤,你是否得到誤報,沒有答案,它是否永遠運行,是否給出了錯誤的答案,它只是有時工作,你是否真的沒有運行它,它不會編譯,[...]? – Servy