使用rand()生成变量周围的数字?(C++)

Using rand() to generate numbers around a variable?(C++)

本文关键字:数字 周围 C++ rand 使用 变量      更新时间:2023-10-16

我正在用c++制作一个名为"House Evolution"的基于文本的小游戏,以获得乐趣。游戏包括"在沙发垫下搜索"以获得积分。当你搜索时,游戏应该生成一个从creditRate-5到creditRate+5的随机数。不管creditRate是多少,我该如何使用rand((函数来完成这项工作?以下是示例代码:

#include <iostream>
#include <unistd.h>
#include <string>
#include <cstdlib>
#include <math.h>
int main()
{
    int creditRate = 30; // Just for example.
    int credits;
    int searching;
    while (1) {
        // Yes, I know, infinite loop...
        std::cout << "Credits: " << credits << std::endl;
        std::cout << "Type any key to search for credits: " << std::endl;
        std::cout << "Searching...n";
        usleep(10000000); // Wait 10 seconds
        searching = rand(?????????); // Searching should be creditRate-5 to creditRate+5
        std::cout << "You found " << searching<< " creditsn";
        credits += searching;
    }
}

我的方法是使用兰特%11,得到11个数字的范围,然后将其添加到信用率-5,以覆盖从信用率-5到信用率+5的范围。因此:

searching = rand() % 11 + creditRate - 5;

尝试:searching = rand() % 11 + creditRate-5;这是因为你的范围是11(记住,例如,从-5到5有11个数字(,下限是creditRate-5。

使用<random>标头而不是rand(),因为<random>提供了正确生成这些分发的工具,而不是让您自己生成。

#include <iostream>
#include <thread>
#include <random>
int main()
{
    int creditRate = 30; // Just for example.
    // Searching should be creditRate-5 to creditRate+5
    std::uniform_int_distribution<> random_credit_amount(creditRate - 5, creditRate + 5);
    int credits = 0;
    // arrange a source of randomness
    std::random_device r;
    std::seed_seq seed{r(),r(),r(),r(),r(),r()};
    std::mt19937 pRNG(seed);
    while (true) {
        // Yes, I know, infinite loop...
        std::cout << "Credits: " << credits << 'n';
        std::cout << "Type any key to search for credits: " << 'n';
        std::cout << "Searching...n";
        std::this_thread::sleep_for(std::chrono::seconds(10)); // Wait 10 seconds
        int searching = random_credit_amount(pRNG);
        std::cout << "You found " << searching<< " creditsn";
        credits += searching;
    }
}

<random>甚至提供了比典型的均匀分布更高级的选项。例如,使用"正态"(也称为"钟形曲线"(分布,您可以让更接近creditRate的值比更远的值更有可能,而不是让从creditRate - 5creditRate + 5的每个值都有同样的可能性:

// credits found should be near creditRate
std::normal_distribution<> random_credit_amount(creditRate, 5);

然后在循环中:

    int searching = std::round(random_credit_amount(eng));

(你根本不需要改变循环中的代码,但它会使分布有点偏斜。执行适当的舍入可以避免偏斜。(


请注意我所做的另一项更改,用标准this_thread::sleep_for替换了非标准usleep。请注意,此代码使注释完全多余:

std::this_thread::sleep_for(std::chrono::seconds(10)); // Wait 10 seconds

人们可以很容易地要求几微秒或几个小时的睡眠时间

std::this_thread::sleep_for(std::chrono::hours(2));
std::this_thread::sleep_for(std::chrono::microseconds(50));