0

我有当前的编码,我觉得它好像接近我需要的,但我似乎无法让它为我想要的工作。我试图让它输出输入的两个数字的最高公因数。

            i = myInt;

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

                }
                else
                    i--;
                goto;
            }
4

2 回答 2

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;
    }
}
于 2012-11-14T18:22:23.650 回答
-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.

于 2012-11-14T17:51:57.617 回答