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

时间:2015-07-27 20:25:52

标签: c++ random

我正在用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<< " credits\n";
        credits += searching;
    }
}

3 个答案:

答案 0 :(得分:3)

我将采用的方式是使用rand%11,获得11个数字的范围,然后将其加到信用率-5,以涵盖从creditrate-5到creditrate + 5的范围。 所以:

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

答案 1 :(得分:2)

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

答案 2 :(得分:1)

使用<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<< " credits\n";
        credits += searching;
    }
}

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

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

然后在循环中:

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

(你根本不需要更改循环中的代码,但它会稍微扭曲分布。执行适当的舍入可以避免偏斜。)

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

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));