C++中的无限循环

Infinite Loops in C++

本文关键字:无限循环 C++      更新时间:2023-10-16

当我尝试运行这个程序时,我不断收到无限循环错误。有人能帮帮我并告诉我为什么吗?如有任何协助,我们将不胜感激。谢谢

    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;
}

第二个问题是,您通过值传递countIncrement,如果您想更新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);

如果您还有其他问题,请询问。