首页 文章

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

提问于
浏览
0

好的,所以我正在尝试使用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

    其他用户有一个好点 . 我只想补充一点,因为您刚开始时应该学习一些简单的方法来帮助调试和查找代码问题 . 初学者使用的一个非常常见的工具是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;
    

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

  • 1

    num1 =除数:

    5/5 = 1

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

  • 1

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

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

  • 1

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

  • 6

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

    你可能想要的:

    while ( (num1 % divisor != 0 ) || ( num2 % divisor != 0 ) )
    {
    
       divisor--;
       opers++;
    }
    

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

  • 1

    divisor == num1最初,所以(num1%divisior!= 0)不是真的 .

相关问题