使用C++随机数引擎和分布类对象设计老虎机

本文介绍了一个使用C++实现的随机数生成器,通过随机数引擎和分布类生成指定范围内的随机整数,并设计了一个验证函数,用于检查生成的随机数是否满足特定条件。文章详细展示了如何在程序中应用这些功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

随机数库random中随机数引擎random-number engins和随机数分布类random-number distribution
param_gen.h

#pragma once
#include <random>

class Random {
public:
    Random(unsigned min, unsigned max)
        : min(min), max(max), u(min, max) {}
    unsigned get_random_int() {
        return u(e);
    }
private:
    unsigned min = 0;
    unsigned max = 9;
    std::uniform_int_distribution<unsigned> u;
    std::default_random_engine e;
};

utility.h

#pragma once
#include <iostream>
#include <string>
#include <vector>

bool validate(const std::vector<unsigned> &v) {
    bool flag = true;
    for (auto itr = v.cbegin(); itr != v.cend(); ++itr) {
        if (*itr != 6) {
            flag = false;
        }
    }
    return flag;
}

void go_through(const std::vector<unsigned> &v) {
    for (const auto &i:v) {
        std::cout << i << " ";
    }
    std::cout << std::endl;
}

main.cpp

#include <iostream>
#include <string>
#include <vector>
#include "param_gen.h"
#include "utility.h"

using namespace std;

int main() {
    cout << "Welcome to tiger machine" << endl;
    Random rom(0, 9);
    char cmd;
    cout << "Get start? Y/N" << endl;
    while (cin >> cmd && cmd =='Y') {
        vector<unsigned> v;
        for (size_t i = 0; i < 3; ++i) {
            v.push_back(rom.get_random_int());
        }
        go_through(v);
        if (validate(v)) {
            cout << "Congratulation! You get 666" << endl;
        } else {
            cout << "Ops, try it again? Y/N" << endl;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值