2009-10-22 71 views
0

好的,所以我试图用while循环创建一个程序来查找两个数字的最大公约数。这是我想出的。但是,从我所知道的情况来看,当我运行它时,程序似乎完全跳过了循环。 (操作符保持为0,除数总是等于num1)。任何人都可以帮助新手?这个while循环为什么不起作用?

/* 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; 
+3

我建议您学习如何使用调试程序逐句通过代码。 – StackedCrooked 2009-10-22 15:10:18

回答

6

只要其中一个modulo返回非0,while循环终止。 (所以,如果你的任何输入立即在0从模成果,循环将不进入)

你可能想什么:

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

    divisor--; 
    opers++; 
} 

这继续循环,直到两个模运算导致0

+0

或'!(num1%divisor == 0 && num2%divisor == 0)' – dotjoe 2009-10-22 14:08:39

+0

oooo。提醒我电气工程101. Notted输入和门相当于未输出或门。 – 2009-10-22 15:48:07

1

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

1

num1 == divisor因此num1 % divisor == 0和循环条件是错误的。您想使用||而不是&&

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

0

NUM1 =除数:

5/5 = 1

所以这个(!NUM1%除数= 0),结果始终为true和其他不,你永远不会进入。

1

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

+0

错误还是次优? – Bill 2009-10-22 14:54:22

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; 

所以你可以做你想要的输出,但这只是为了显示它背后的想法。我希望这可以帮助您在将来的调试中。此外,实际的调试程序比这种方法更先进;但这适用于简单的问题。

相关问题