c++ - 获取多个随机数的问题

标签 c++ winapi random

<分区>

Possible Duplicate:
Recommended way to initialize srand?

我正在从 AVI 中提取帧。我希望用户选择他是想获取用户给定范围内的所有帧还是获取所有可用帧或获取用户给定数量的随机帧。前两个功能工作得很好。但是对于随机帧,我总是只得到一帧,而不是给定的帧数。所以,这里用户设置帧数:

case AVIINF_BUTTON_GETRAND:
            extractmode=-1;
            GetDlgItemText(aviinfhwnd, AVIINF_EDIT_GETRAND, charfrQuantity, 20);
            frQuantity = atoi(charfrQuantity);
            ExtractAVIFrames(extractmode, frFrom, frTo, frQuantity);
            EndDialog(aviinfhwnd, IDCANCEL);
break;

然后在 ExtractAVIFrames() 中执行所有初始化等操作之后:

case -1://get x random frames

            for (int i=1; i<=frQuantity; i++)
            {
                index= GetRandomInt(iNumFrames);
                BYTE* pDIB = (BYTE*) AVIStreamGetFrame(pFrame, index);
                CreateFromPackedDIBPointer(pDIB, index);
            }
break;

调用 GetRandomInt()

int GetRandomInt(int randNumScale)
{
    srand((unsigned)time(0));
    int random_integer;
    int range=randNumScale;
    random_integer = (rand()%range)+1;
    return random_integer;
}

所以,这应该调用 GetRandomInt() 函数 frQuantity-times 我应该有 frQuantity BMP,对吧?但我没有,我总是只得到一个(随机的一个)。似乎在每次调用 GetRandomInt 后返回与上一次调用相同的数字。 怎么了? 谢谢

最佳答案

您正在使用相同的种子初始化伪随机 数字生成器。仅初始化一次,并使用半随机(例如,系统时钟中的毫秒数)数字。

关于c++ - 获取多个随机数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6272966/

相关文章:

c# - 生成随机加权值

c++ - 在 C++ 中设置 `std::unordered_set` 中初始桶数的策略

c++ - 为什么模板函数中的strcmp()返回不同的值?

c++ - 了解低级鼠标和键盘钩子(Hook)(win32)

python - 如何停止获得重复的随机值?

r - 在 R 中生成 3 个总和为 1 的随机数

c++ - 在静态库中硬编码的代码文件和头文件路径?

c++ - 为 QML 的 ListView 公开 QObjects 的 QAbstractListModel。好的做法?

winapi - 为什么从 Rust 调用 SystemParametersInfo 来设置壁纸会将其设置为黑色?

从其他进程单击其他窗口的按钮