C++中的无限循环
Infinite Loops in C++
当我尝试运行这个程序时,我不断收到无限循环错误。有人能帮帮我并告诉我为什么吗?如有任何协助,我们将不胜感激。谢谢
void Increment(int);
int main()
{
int count = 1;
while(count < 10)
cout << "the number after " << count; //Increment function
Increment(count); //count+1
cout << " is " << count << endl;
return 0;
}
void Increment (int nextNumber)
{
nextNumber++; //parameter +1
}
您传递的是值而不是引用:
改为:
void Increment (int& nextNumber)
{
nextNumber++; //parameter +1
}
此外,您还缺少while循环的大括号。
如果while
循环使用多行,则需要大括号。实际上,为了避免混淆,您应该始终使用大括号。此外,Increment
函数应该通过引用获取其参数,这样它就不会对副本进行操作(无限循环的另一个原因):
void Increment(int&);
int main()
{
int count = 1;
while (count < 10)
{
std::cout << "the number after " << count;
Increment(count);
std::cout << " is " << count << std::endl;
}
}
void Increment(int& nextNumber)
{
nextNumber++;
}
while(count < 10)
cout << "the number after " << count; //Increment function
这是一个无限循环,因为计数总是相同的值,并且不被这个循环更改。
这就是为什么必须在循环周围使用括号({}
),否则会出现这样的错误。
重新编写代码,并说明正在发生的事情:
void Increment(int);
int main()
{
int count = 1;
while(count < 10)
{
cout << "the number after " << count; //Increment function
}
Increment(count); //count+1
cout << " is " << count << endl;
return 0;
}
void Increment (int nextNumber)
{
nextNumber++; //parameter +1
}
Increment
函数不执行任何操作,因为它按值接受参数nextNumber
。这意味着它对传递给它的变量的副本进行操作,因此当函数退出时,它的更改将丢失。相反,通过引用:使其接受变量
void Increment (int &nextNumber)
{
nextNumber++; //parameter +1
}
您还必须在while
循环中使用{}
:包围代码
while(count < 10)
{
cout << "the number after " << count; //Increment function
Increment(count); //count+1
cout << " is " << count << endl;
}
while(count < 10)
cout << "the number after " << count; //Increment function
您需要括号,否则while只会一次又一次地执行cout,而不会执行增量函数
有两个主要问题,while
循环缺少大括号,应该如下所示:
while(count < 10)
{
cout << "the number after " << count; //Increment function
Increment(count); //count+1
cout << " is " << count << endl;
}
第二个问题是,您通过值传递count
到Increment
,如果您想更新count
,可以通过引用传递:
void Increment (int &nextNumber)
您通过值传递count
,因此它不会递增。传递值意味着在函数中使用变量的本地副本,并且它不会影响原始变量。您需要使用& operator
传递地址。你可以使用这个:-
void Increment (int& nextNumber)
{
nextNumber++;
}
您还没有将while循环用大括号{ }
括起来,这可能会对程序的执行产生不希望的影响。
通过值传递的问题。当您将数字传递给Increment时,它会生成一个名为nextNumber的副本并将其递增。此更改不会反映在已发送的参数中。因此,计数从未增加。
要更正,您可以从增量返回一个值,也可以调用be引用。
按价值调用
int Increment (int nextNumber)
{
return nextNumber+1; //parameter +1
}
这里的呼叫声明是:
count=Increment(count);
参考呼叫:
我假设你不知道这意味着什么,基本上你会传入变量的地址,这样你就不会在增量中复制,而是处理原始变量本身。
void Increment (int& nextNumber)
{
nextNumber++; //parameter +1
}
这里的呼叫声明:
Increment(count);
如果您还有其他问题,请询问。
- 过载'operator new'如何导致无限循环?
- C++正则表达式无限循环
- 程序在尝试猜测它选择的随机数时进入无限循环?
- 遍历链表时的无限循环
- 循环链表:无限循环
- 比较两个字符串后卡在无限循环中
- 在做一段时间内检查字符的无限循环
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 在这个无限循环中,当输入 0 时终止,当输入 int 范围之外的任何内容时,程序行为不正常
- 可能的无限循环
- 超出 int 的值范围后的无限循环
- 为什么这段代码会导致无限循环?
- 运行无限循环的最小二叉树问题
- 在分配和发布递增循环迭代器时C++无限循环(gcc 错误?
- 连接线程时的无限循环
- 为什么这种方法会进入无限循环?
- 由于QTextStream的无限循环
- Qt 在另一个线程中无限循环
- 从文件 C++ 读取时的无限循环
- 试图找出为什么我的代码保持无限循环