【问题标题】:How can you get a random number on GBDK?如何在 GBDK 上获得随机数?
【发布时间】:2021-02-08 15:57:27
【问题描述】:

我是 C 和 GBDK 的新手,我想编写一个在 0 和 1 之间决定的随机数生成器。 就像一个“黑客”模拟器。

我尝试了很多来自 Internet 的示例。但没有一个有效。

我上次尝试的输出截图:https://i.ibb.co/f8G39vX/bgberrors.png

上次尝试代码:

#include <gb/gb.h>
#include <stdio.h>
#include <rand.h>

void init();

void main() 
{
        init();
        while(1)
        {
            UINT8 r = ((UINT8)rand()) % (UINT8)4;
            printf(r);
        }
}

void init()
{
    DISPLAY_ON;
}

我怎样才能完成它?

【问题讨论】:

  • 您需要floatdouble 才能从0 到1,而在C 中printf() 不能这样工作。例如printf("%f\n", 1.0 * rand() / RAND_MAX);
  • 别忘了seed你的RNG。
  • @WeatherVane 'main.c:12: error 20: Undefined identifier 'RAND_MAX'' 这在构建时出现。
  • #include &lt;stdlib.h&gt;(并删除rand.h,但也许GBDK有自己的最大值)。如果您对某些东西不熟悉,则应该前往手册页。
  • @WeatherVane 'main.c:12:警告 112:函数 'rand' 隐式声明。 main.c:12: error 20: Undefined identifier 'RAND_MAX'' 现在有一个警告。我很困惑:s

标签: c gbdk


【解决方案1】:
#include <gb/gb.h>
#include <stdint.h>
#include <stdio.h>
#include <rand.h>

void init();

void main()
{
        init();
        printf(" \n\n\n\n\n\n\n\n    PRESS START!\n");
        // abuse user input for seed generation
        waitpad(J_START);
        uint16_t seed = LY_REG;
        seed |= (uint16_t)DIV_REG << 8;
        initrand(seed);
        while(1)
        {
            UINT8 r = ((UINT8)rand()) % (UINT8)2;
            printf("%d", r);
        }
}

void init()
{
        DISPLAY_ON;
}

使用 GBDK-2020 4.0.3 测试

还要检查 GBDK-2020 中的“rand”示例。

关于cmets:

是的,GBDK 有它自己的库(包括标准库)。它可能是 20 年前 SDCC 的 lib 的一个分支。当前的 SDCC 在 stdlib.h 中有 rand(),但 GBDK-2020 没有。 Max 是 0xFF,我不知道它的定义。

应该尽可能避免浮点,它完全是在软件中完成的,没有硬件支持。编译器并不真正支持 Double 并回退到 float。

没有手册页,文档可在此处获得:https://gbdk-2020.github.io/gbdk-2020/docs/api/rand_8h.html 或阅读 gbdk-2020 的 gbdk_manual.pdf

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-02
    • 1970-01-01
    • 2023-03-27
    • 2015-01-14
    • 2021-06-20
    相关资源
    最近更新 更多