首页 > 解决方案 > 为什么这个方法会进入无限循环?

问题描述

尽管使用了递减运算符,但我的 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; 
    } 

标签: c++stringwhile-loop

解决方案


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

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

推荐阅读