当我尝试编译时说“ h”不是初始化的。但是,有时会根据我在下面的工作而起作用。我什么时候不来这里?

发布于 2025-02-03 21:23:01 字数 523 浏览 0 评论 0原文

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    //get height
    int h;
    do
    {
        get_int("Height: ");

    } while (h < 1 || h > 8);

    //
    for (int y = 7 - h; y > 0; y--)
    {
        if (y < 0)
            printf("#  #");
        else
            printf(" ");
    }

    for (int x = 0; h > x; x++)
    {
        printf("#");
    }
}

我整天都在工作,但我只是没有得到它。有时,当我检查时,我的代码与课程相同,但它行不通。我不确定这是我的间距还是什么。否则我将解决一个错误,并在我没有碰到该区域后才继续工作以使其恢复。感觉完全迷失了。

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    //get height
    int h;
    do
    {
        get_int("Height: ");

    } while (h < 1 || h > 8);

    //
    for (int y = 7 - h; y > 0; y--)
    {
        if (y < 0)
            printf("#  #");
        else
            printf(" ");
    }

    for (int x = 0; h > x; x++)
    {
        printf("#");
    }
}

I have been working on this all day and I am just not getting it. sometimes when I check, my code is identical to the lesson yet it won't work. I am not sure if it is my spacing or what. or I'll fix an error and keep working only for it to come back after I had not even touched that area since I got it working. feeling completely lost.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

失与倦" 2025-02-10 21:23:01

您的代码具有未定义的行为,因为h是未定式化的,并且您永远不会存储get_int的返回值(“ height:”)中。

h的值是未定义的,因此对于程序的不同运行可能会有所不同,从而解释了观察到的行为。修复很容易:只需写h = get_int(“ height:”);do/while循环中。

这是一个修改值:

#include <cs50.h>
#include <stdio.h>

int main() {
    int h;

    do  {
        h = get_int("Height: ");

    } while (h < 1 || h > 8);

    for (int y = 7 - h; y > 0; y--) {
        if (y < 0)
            printf("#  #");
        else
            printf(" ");
    }

    for (int x = 0; h > x; x++) {
        printf("#");
    }
    return 0;
}

Your code has undefined behavior because h is uninitialized and you never store the return value of get_int("Height: ") into it.

The value of h is undefined, so it can be different for different runs of your program, thus explaining the observed behavior. The fix is easy: just write h = get_int("Height: "); in the do/while loop.

Here is a modified value:

#include <cs50.h>
#include <stdio.h>

int main() {
    int h;

    do  {
        h = get_int("Height: ");

    } while (h < 1 || h > 8);

    for (int y = 7 - h; y > 0; y--) {
        if (y < 0)
            printf("#  #");
        else
            printf(" ");
    }

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