0

好的,所以我正在尝试使用 while 循环创建一个程序来找到两个数字的最大公约数。这就是我想出的。但是,据我所知,该程序在我运行时似乎完全跳过了循环。(opers 保持为 0,divisor 总是返回等于 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

只要其中一个模返回非 0,while 循环就会终止。(因此,如果您的任何输入立即导致模数为 0,则不会进入循环)

你可能想要的:

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

   divisor--;
   opers++;
}

这将继续循环,直到两个模运算结果为 0。

于 2009-10-22T14:01:19.297 回答
1

divisor == num1 最初,所以 (num1 % divisior != 0) 不正确。

于 2009-10-22T14:02:26.243 回答
1

num1 == divisor所以num1 % divisor == 0循环条件为假。您想使用||而不是&&.

您可能还想使用更好的算法。我认为欧几里得想出了一个。

于 2009-10-22T14:02:30.220 回答
1

它不起作用,因为您的算法是错误的!有关正确的 GCD 算法,请参见此处

于 2009-10-22T14:03:44.893 回答
1

其他用户有一个很好的观点。我只想补充一点,既然你刚开始,你应该学习一些简单的方法来帮助调试和发现代码问题。初学者使用的一种非常常见的工具是打印语句。如果您在关键区域添加打印语句,那么您可以很容易地找到问题。

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 % divisor != 0 ) 总是评估为 true 而另一个不评估,你永远不会进入。

于 2009-10-22T14:02:31.547 回答