c++ - 生成范围内的随机数c++

标签 c++ c random

<分区>

我正在使用 ncurses 库来构建游戏。我无法生成正确的随机数。下面的 while 循环需要不断生成随机数,直到它们在 1 到 45 之间(这是我在标准屏幕上的 y 轴限制)。我不知道我做错了什么,因为 while 循环条件对我来说看起来很好。问题是 while 循环开始无限运行。除了在最后打印生成的数字外,我什么也没做,因为我只想看到生成了正确的数字。谁能帮我解决这个问题?以下是我的主要内容。

int main()
{
int r,c,x=0;
initscr();
raw();
keypad(stdscr, TRUE);
noecho();
//mvprintw(22,45,"<");
getmaxyx(stdscr,r,c);

int n,n2 = 0;

while((n<1)||(n>45)){
srand (time(NULL));
n = rand();
srand (time(NULL));
n2 = rand();
}
mvprintw(4,10,"First Random Number: %d\n", n);
mvprintw(5,10,"Second Random number: %d\n", n2);

getch();
endwin();
return 0;
}

最佳答案

这是用 C++ 实现的方法:

#include <iostream>
#include <random>

int main()
{
    std::random_device rd;
    std::mt19937 gen( rd());
    std::uniform_int_distribution<> dis( 1, 45);

    for (int n=0; n<1000; ++n)
        std::cout << dis(gen) << ' ';
    std::cout << '\n';
}

使用 rand() % x 是一个有缺陷的设计,因为在不均匀划分范围时引入了偏差。你可以阅读this了解有关 rand() % x 引入的偏差的更多信息。

关于c++ - 生成范围内的随机数c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26301410/

相关文章:

c++ - 传递包含 const 内容的 vector

c++ - 声音 API Ubuntu Linux

c++ - NCurses 不恢复终端行为

c - 在C中将字符串中最长的单词升级为大写字母

c - 将节点添加到链表时出现段错误

java - 在对象实例之间随机共享?

c++ - 结合 rand() 和 srand() 以获得更好的性能

c++ - 通过 Winsock 发送键盘缓冲区

CYGPATH 不会从 makefile 中调用

C++ exponential_distribution模板类生成非精确随机数