我的循环永远不会结束......我不明白为什么。有任何想法吗?

My loop never ends...and I dont understand why. Any ideas?

我想找出为什么我的循环永远不会结束。我正在尝试取两个数字,从最小的开始,一直除以 4,直到达到 0。

#include<iostream>
using namespace std;

int main
{
    int x, y, answer = 0;

    cout << "dude enter two numbers " << endl;
    cin >> x >> y;

    //this is trouble statement
    for (int num = x; num <= y; num++) 
    { 
        while (num != 0)

            answer = num / 4;
            cout << answer << " ";
        }
    }
    return 0;
}

条件while (num != 0)就是问题所在。

因为,您没有在 while 循环中修改 num,因此 num 的值永远不会改变。 因此,无限循环。

对您的代码进行一些更改就足够了:

#include<iostream>
using namespace std;    
int main()
{
    int x, y, answer = 0;
    cout << "dude enter two numbers " << endl;
    cin >> x >> y;
    for (int num = x; num <= y; num++) 
    { 
        //Created a temporary variable.
        int temp = num;
        //All operations on the temporary variable.
        while (temp != 0)
        {
            temp = temp/ 2;
            cout << temp << " ";
        }
        cout<<endl;
    }
    return 0;
}