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

C++ 为什么这个while循环不起作用?,c++,c,while-loop,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 inpu

好的,我正在尝试创建一个程序,使用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;

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

您可能想要的:

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

   divisor--;
   opers++;
}

这将继续循环,直到两个模运算都得到0。

除数==num1,因此num1%divisior!=0不是真的

num1==除数,因此num1%除数==0,循环条件为false。您希望使用| |而不是&

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

num1=除数:

5/5=1


所以这个num1%除数!=0的计算结果始终为true,而另一个则不为true,您将永远无法输入。

它不起作用,因为您的算法错误!有关正确的GCD算法,请参阅。

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

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;

所以你可以随心所欲地输出,但这只是为了展示背后的想法。我希望这对您以后的调试有所帮助。此外,还有比这种方法更先进的实际调试程序;但这适用于简单的问题。

或!num1%除数==0&&num2%除数==0oooo。提醒我,如果电气工程101。Notted input and gate相当于Notted output or gate。我建议您学习如何使用调试器单步执行代码。