0

さて、私はwhileループを使用してプログラムを作成し、2つの数値の最大公約数を見つけようとしています。これが私が思いついたものです。しかし、私が知る限り、プログラムを実行すると、プログラムはループを完全にスキップしているように見えます。(opersは0のままで、除数は常にnum1に等しくなります)。初心者を助けることができる人はいますか?

/* Define variables for divisors and number of operations */

int num1, num2, divisor, opers;
opers = 0;

/* Prompt user for integers and accept input */

cout << "Please enter two integers with the smaller number first, separated by a space. ";
cout << endl;
cin >> num1 >> num2;

/* Make divisor the smaller of the two numbers */

divisor = num1;

/* While loop to calculate greatest common divisor and number of calculations */

while ( (num1 % divisor != 0 ) && ( num2 % divisor != 0 ) )
{

   divisor--;
   opers++;
}

/* Output results and number of calculations performed */

cout << "The greatest common divisor of " << num1 << " and " << num2 << " is: ";
cout << divisor << endl << "Number of operations performed: " << opers;
4

6 に答える 6

6

これらのモジュロの1つが0以外を返すとすぐに、whileループが終了します。(したがって、入力のいずれかがモジュロからすぐに0になる場合、ループは開始されません)

あなたがおそらく欲しいもの:

while ( (num1 % divisor != 0 ) || ( num2 % divisor != 0 ) )
{

   divisor--;
   opers++;
}

これにより、両方のモジュロ演算が0になるまでループが続行されます。

于 2009-10-22T14:01:19.297 に答える
1

除数==最初はnum1なので、(num1%divisior!= 0)は真ではありません。

于 2009-10-22T14:02:26.243 に答える
1

num1 == divisorしたがってnum1 % divisor == 0、ループ条件はfalseです。||の代わりに使用したい&&

また、おそらくより良いアルゴリズムを使用したいと思うでしょう。ユークリッドが思いついたと思います。

于 2009-10-22T14:02:30.220 に答える
1

アルゴリズムが間違っているため、機能しません。適切なGCDアルゴリズムについては、ここを参照してください。

于 2009-10-22T14:03:44.893 に答える
1

他のユーザーには良い点があります。始めたばかりなので、コードのデバッグと問題の発見に役立ついくつかの簡単な方法を学ぶ必要があることを付け加えたいと思います。初心者が使用する非常に一般的なツールの1つは、printステートメントです。重要な領域に印刷ステートメントを追加すると、問題を非常に簡単に見つけることができます。

cout << "Please enter two integers with the smaller number first, separated by a space. ";
cout << endl;
cin >> num1 >> num2;

/* Make divisor the smaller of the two numbers */

divisor = num1;

cout << "Checking values ..." << endl;
cout << "num1 = " << num1 << endl;
cout << "num2 = " << num2 << endl;
cout << "divisor = " << divisor << endl;

/* While loop to calculate greatest common divisor and number of calculations */

cout << "about to start loop" << endl;
while ( (num1 % divisor != 0 ) && ( num2 % divisor != 0 ) )
{

   divisor--;
   opers++;
   cout << "In the loop and divisor = " << divisor << " and opers = " << opers << end;
}
cout << "after loop" << endl;

したがって、出力は好きなように行うことができますが、これはその背後にある考え方を示すためだけのものです。これが将来のデバッグに役立つことを願っています。また、この方法よりもはるかに高度な実際のデバッグプログラムがあります。しかし、これは単純な問題に対しては機能します。

于 2009-10-22T14:06:57.973 に答える
0

num1 =除数:

5/5 = 1

したがって、これ(num1%除数!= 0)は常にtrueと評価され、もう一方はtrueと評価されないため、入力することはありません。

于 2009-10-22T14:02:31.547 に答える