rand()在递归函数中产生高于设定范围的数字

问题描述 投票:-1回答:2

我的理解是这产生了一个介于10和偏移之间的随机数:

random = (rand() % 10) + offset;

offset增加1但从不超过10,但是当我运行此代码时,变量random设置为> 10的数字。

有问题的代码:

#include "pch.h"
#include <cstdlib>
#include <Windows.h>
#include <iostream>
using namespace std;

void gen(int offset)
{
    int random;

    if (offset != 10)
    {
        random = (rand() % 10) + offset;
        cout << "random should be between: " << 10 << " and " << offset << endl;
        cout << "random: " << random << endl << endl;
        Sleep(500);
        gen(++offset);
    }
}

int main()
{
    srand(373);

    gen(1);
    cin.get();
}

和输出:

随机应介于:10和1之间

随机:7

随机应介于:10和2之间

随机:11

随机应介于:10和3之间

随机:3

随机应介于:10和4之间

随机:13

随机应介于:10和5之间

随机:10

随机应介于:10和6之间

随机:13

随机应介于:10和7之间

随机:16

随机应介于:10和8之间

随机:14

随机应介于:10和9之间

随机:18

c++ recursion random function-call
2个回答
1
投票

(rand() % 10)返回范围[0,9]中的值,因此(rand() % 10) + offset将返回范围[offset,offset + 9]中的值。

如果你想在范围[offset,10]中返回值,你需要(rand() % (11 - offset)) + offset,偏移量小于11。

你也应该使用std::uniform_int_distribution来获得范围内的随机整数。


0
投票

(rand() % 10)导致0到9之间的数字,然后你加上offset第一次rand() % 10)导致6,你加入1.因此7。第二次,rand() % 10)得到9,你加了2,因此11

© www.soinside.com 2019 - 2024. All rights reserved.