需要帮助解决无限循环问题

发布于 2024-10-02 21:37:19 字数 382 浏览 0 评论 0原文

这是我的代码的简化版本:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无名指的心愿 2024-10-09 21:37:20

如果 *s 是数字,则 s 不会递增,考虑删除 else 子句,使代码如下:

while (*s)
{
    if (isdigit(*s))
        t += *s - '0';

    ++s;
}

s is not incremented if *s is a digit, consider removing the else clause, making the code into this:

while (*s)
{
    if (isdigit(*s))
        t += *s - '0';

    ++s;
}
み格子的夏天 2024-10-09 21:37:20

@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.

淡淡的优雅 2024-10-09 21:37:20

你的 else 条件不满足

试试这个

if (isdigit(*s))

t += *s - '0';

 s++;

your else condition is not fulfilled

try this

if (isdigit(*s))

t += *s - '0';

 s++;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文