我的循环永无止境.我不明白为什么.任何想法
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;
}
相关文章:
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 为什么瓦尔格林德在不释放恶意内存后没有报告任何问题?
- 为什么 std::lerp 不适用于任何已实现所需操作的类型?
- 为什么我的 HWID 锁接受任何acceptedSerial_2值
- 为什么静态数组成员变量在调用对象的实例后不显示任何内容?
- 可能我知道为什么这段代码没有给出任何输出吗?
- 为什么下面的Hello World程序在PowerShell上没有显示任何输出?同一程序在CMD上显示正确的输出
- 为什么 c++ 中的 main() 函数不采用除 int 和 void 之外的任何其他返回类型
- 为什么这个程序对投掷不做任何事情?
- 您好,我实际上想了解以下代码.有人可以详细说明代码它到底在做什么吗?为什么它会在第 31 行崩溃
- 执行此代码时,它不显示任何输出.为什么?
- 我是C++新手,我想知道,为什么在c ++中使用纯虚函数?为什么要使用纯虚函数?
- 给定一个 3 x 3 矩阵或任何 n x n 矩阵,为什么我的以下函数找不到对角线差异?
- 为什么我的突变器函数没有设置任何内容?还是我的构造函数?
- 我想知道为什么"std::unique_ptr<int> foo(新 int)"是合法的,因为"std::<int>unique_ptr"要求输入参数类型应该是"int"?
- 如何在 if 语句中声明对象并在任何我想的地方使用它?
- 我的循环永无止境.我不明白为什么.任何想法
- 为什么我想使用托管(C#和.NET)或本机代码进行Windows API开发
- 为什么我想在C++中实现我自己的双链表
- ' std::kill_dependency '做什么,为什么我想使用它