C ++无限循环问题

时间:2016-04-17 06:24:05

标签: c++ infinite-loop

我不确定问题是什么。我添加了“cout<< count;”到if语句,看看为什么没有返回值'val'。

但现在我看到发生了无限循环。

我实际上是在计算num = 0需要多少循环。

起初我以为是num = count在循环中。

有什么建议吗?提前致谢。

#include <iostream>
using namespace std;

// hailstone function prototype
int hailstone(int &num);


int main()
{
    int val;

    cout << "Enter integer" << endl;
    cin >> val;

    hailstone(val);

    cout << val << endl;

    return 0;


}

// Pass values by reference to hailstone function header
int hailstone(int &num)
{   

    do
    {
        int count = 0;    

        // If num is even
        // Divide by two
        if(num % 2 == 0)
        {
            num = (num / 2);
            count++;
            cout << count;

        }

        // If num is odd
        // Multiply by 3 and add 1
        else if(num % 2 != 0)
        {
            num = (num * 3) + 1;
            count++;
            cout << count;

        }
    // Assign the number of steps to num
    num = count;

    } while(num > 0);

    // Return the number of steps
    return num;
}

4 个答案:

答案 0 :(得分:0)

这里有一些问题,但最相关的是这一行:

// Assign the number of steps to num
num = count;

根据冰雹序列的规则更新后,你基本上会重置num。因为'count'在每个循环开始时初始化,然后在'if'或'else if'块中迭代一次,它总是一个。因此,在每个循环结束时,num始终为1.

答案 1 :(得分:0)

无论您是num = num/2;(对于偶数)还是num = (num * 3) + 1(对于奇数),该数字都不会变为0 or less。这就是为什么你的代码运行无限时间的原因。因此,您需要在函数while (num > 0);内将行while(num > 1);更改为hailstone(可能是第54行)。如下所示:

旧代码:

int hailstone(int &num)
{   

do
{
    int count = 0;    

    // If num is even
    // Divide by two
    if(num % 2 == 0)
    {
        num = (num / 2);
        count++;
        cout << count;

    }

    // If num is odd
    // Multiply by 3 and add 1
    else if(num % 2 != 0)
    {
        num = (num * 3) + 1;
        count++;
        cout << count;

    }
// Assign the number of steps to num
num = count;

} while(num > 0); //You need to change this line

// Return the number of steps
return num;
}

新代码:

int hailstone(int &num)
{   

do
{
    int count = 0;    

    // If num is even
    // Divide by two
    if(num % 2 == 0)
    {
        num = (num / 2);
        count++;
        cout << count;

    }

    // If num is odd
    // Multiply by 3 and add 1
    else if(num % 2 != 0)
    {
        num = (num * 3) + 1;
        count++;
        cout << count;

    }
// Assign the number of steps to num
num = count;

} while(num > 1); //Here is the change

// Return the number of steps
return num;
}

另一个问题:您声明num = count(第52行),它不会返回实际值(如果您的代码用于计算循环次数)。示例:如果输入 12 ,则循环将运行 10 次,但您的代码将打印 11 ,我不认为这条线是必需的。在count循环中断后返回do-while变量的值。 感谢

答案 2 :(得分:-1)

显然要么'if'或'else if'要满足将count增加到1的条件,并且分配num = count使num = 1,所以(num> 0)总是为true。所以循环永远继续

答案 3 :(得分:-2)

do
{
  int count = 0;    

  if (num % 2 == 0)
  {
    num = (num / 2);
    count++;
    cout << count;
  }
  else if(num % 2 != 0)
  {
    num = (num * 3) + 1;
    count++;
    cout << count;
  }

  num = count;

} while (num > 0);