为什么这个while循环不起作用?

时间:2009-10-22 13:56:43

标签: c++ c while-loop

好的,所以我正在尝试使用while循环创建一个程序来查找两个数字的最大公约数。这就是我提出的。但是,据我所知,程序似乎在我运行时完全跳过了循环。 (操作数保持为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;

6 个答案:

答案 0 :(得分:6)

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

你可能想要什么:

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

   divisor--;
   opers++;
}

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

num1 == divisor所以num1 % divisor == 0并且循环条件为false。您想使用||代替&&

您可能还想使用更好的算法。我认为Euclid提出了一个。

答案 3 :(得分:1)

它不起作用,因为你的算法错了!有关正确的GCD算法,请参阅here

答案 4 :(得分: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;

所以你可以根据需要进行输出,但这只是为了展示它背后的想法。我希望这有助于您将来的调试。此外,有一些比这种方法更先进的实际调试程序;但这适用于简单的问题。

答案 5 :(得分:0)

num1 = divisor:

5/5 = 1

所以这个(num1%divisor!= 0)总是评估为true而另一个不评估,你将永远不会进入。