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