【问题标题】:Why does this method go into an infinite loop?为什么这个方法会进入无限循环?
【发布时间】:2020-04-28 11:51:57
【问题描述】:

尽管使用了递减运算符,我的 while 循环已经变成了一个无限循环。你能解释一下为什么会这样吗?一旦条件变为假,它不应该退出while循环吗?

    # include<bits/stdc++.h> 
    using namespace std; 

    const int MAX_CHAR = 26; 

    // Function to print the string 
    void printGrouped(string str) 
    { 
        int n = str.length(); 

        // Initialize counts of all characters as 0 
        int  count[MAX_CHAR] = {0};           

        for (int i = 0 ; i < n ; i++) 
            count[str[i]-'a']++; 

        for (int i = 0; i < n ; i++) 
        {                
            while (count[str[i]-'a']--)
                cout << str[i];
        } 
    } 

    // Driver code 
    int main() 
    { 
        string str = "applepp";           
        printGrouped(str); 
        return 0; 
    } 

【问题讨论】:

  • 当您访问一封信时,您将其计数设置为 -1。你递减直到它的值曾经是 0,所以while 循环总是让计数器保持在 -1。下次你访问它时,它的值不为零并且永远递减。只需将count 的递减放入循环中即可。
  • ... 或将您的条件更改为while (count[str[i]-'a']-- &gt; 0)。此外,您可能对 this post 感兴趣,解释为什么包含 bits/stdc++ 是一种不好的做法。
  • @François Andrieux 非常感谢!
  • @luciole75w 谢谢你!哦,好的,从现在开始将单独包含标题,谢谢

标签: c++ string while-loop


【解决方案1】:

我可以看到,您的 while 循环的“()”括号中有一个表达式。最好有一个条件,你应该把这个表达式放在循环中,然后你需要在这些括号“()”中添加一个与该表达式相关的条件 假设您希望在表达式的值为 -1 时退出循环。我不确定 synatx,只是试图在代码中演示我的逻辑。

  x= count[str[i]-'a']-1;
   While(x!=-1)
   {
     cout << str[i];
     x= count[str[i]-'a']-1;
   }

【讨论】:

    【解决方案2】:

    问题是

    while(count[str[i]-'a']--) { ... }
    

    原因在于表达

    x--
    

    递减x 并返回原始值(递减前)。使用 while 条件,如

    while(x--) { ... }
    

    x 从 1 变为 0 时退出循环,但如果您再次输入 while,那么您就会遇到问题,因为 x 已将其变为 -1,并且不会通过递减它回到零。

    -1 是 while 测试的“真值”,因此它将进入循环并变为 -2,然后再次循环并变为 -3,依此类推,直到出现溢出和未定义的行为。

    循环应该写成

    while(count[str[i]-'a']) {
        count[str[i]-'a']--;
        ....
    }
    

    只有当它还不是零时才减少它

    【讨论】:

      猜你喜欢
      • 2011-04-19
      • 1970-01-01
      • 1970-01-01
      • 2016-03-03
      • 1970-01-01
      • 1970-01-01
      • 2011-11-21
      • 1970-01-01
      相关资源
      最近更新 更多