需要帮助解决无限循环问题
这是我的代码的简化版本:
void calc(char *s)
{
int t = 0;
while (*s)
{
if (isdigit(*s))
t += *s - '0';
else
++s;
}
printf("t = %d\n", t);
}
int main(int argc, char* argv[])
{
calc("8+9-10+11");
return 0;
}
问题在于 while 循环永远运行,尽管我希望它在最后一个数字 1
之后停止。我的预期输出是t = 20
。
This is a simplified version of my code:
void calc(char *s)
{
int t = 0;
while (*s)
{
if (isdigit(*s))
t += *s - '0';
else
++s;
}
printf("t = %d\n", t);
}
int main(int argc, char* argv[])
{
calc("8+9-10+11");
return 0;
}
The problem is with the while loop running forever, though I'm expecting it to stop after the final digit 1
. And my expected output is t = 20
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果
*s
是数字,则s
不会递增,考虑删除 else 子句,使代码如下:s
is not incremented if*s
is a digit, consider removing the else clause, making the code into this:@Hasturkun 已经给了你正确的答案,但这是调试器可以帮助你的一件事,如果你有的话。单步执行代码,您很快就会发现它没有执行
++s;
行。@Hasturkun has given you the right answer, but this is the kind of a thing a debugger could help you with, if you have one available. Step through the code and you'd quickly see it's not executing the
++s;
line.你的 else 条件不满足
试试这个
if (isdigit(*s))
t += *s - '0';
your else condition is not fulfilled
try this
if (isdigit(*s))
t += *s - '0';