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

0 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;
Run Code Online (Sandbox Code Playgroud)

Dou*_* T. 6

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

你可能想要的:

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

   divisor--;
   opers++;
}
Run Code Online (Sandbox Code Playgroud)

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