c++ - 为什么这个方法会进入无限循环?
问题描述
尽管使用了递减运算符,但我的 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;
}
解决方案
我可以看到您的 while 循环的“()”括号中有一个表达式。最好有一个条件,你应该把这个表达式放在循环中,然后你需要在这些括号“()”中添加一个与该表达式相关的条件让我们假设你希望在表达式的值为 -1 时退出循环. 我不确定 synatx,只是试图在代码中演示我的逻辑。
x= count[str[i]-'a']-1;
While(x!=-1)
{
cout << str[i];
x= count[str[i]-'a']-1;
}
推荐阅读
- azure - DSC 扩展 - MSFT_xADDomainController 在 Get-ADDomain PowerShell 上失败
- metal - Metal 结构大小的两个示例似乎相互矛盾
- java - 将空检查转换为可选
- java - 创建一个自定义的android关机系统
- ruby-on-rails - Where Active Record 查询中的 OR 运算符
- dictionary - nginx重定向地图文件夹
- c# - 在字符位置上将字符串拆分为 2 个字符串
- c# - 在对象映射中通过构造函数创建对象
- javascript - JavaScript:Promise.all 结果中有 1 个未定义值
- c++ - 开发 Pong 游戏的错误