我的循环永无止境.我不明白为什么.任何想法

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

本文关键字:为什么 任何想 明白 循环 永无止境 我的      更新时间:2023-10-16

我试图找出为什么我的循环永远不会结束。我正在尝试取两个数字,从最小的数字开始,然后除以 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;
}
相关文章: