0

私は現在のコーディングを持っており、必要なものに近いと感じていますが、私が望むもののためにそれを動作させることができないようです. 入力された2つの数値の最大公約数を出力するようにしようとしています。

            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に、例でわかるように、2つの条件でループ(またはその他)を使用してください。また、検索は小さい数字から始めるべきだと思います(最初に入力した数字は小さい数字である必要はありません)。これはパフォーマンスの点で少し改善されています。これはコードです:

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 に答える