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

时间:2015-01-23 05:59:28

标签: c++ loops for-loop while-loop

我试图找出为什么我的循环永远不会结束。我试图取两个数字,从最小的数字开始,然后保持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;
}

1 个答案:

答案 0 :(得分:2)

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

因为,您没有在num循环中修改while,因此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;
}
相关问题