正如其他人在评论中所说,你真的应该避免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;
}
}