c++ - "Double or Nothing"赌博机代码无法超过15连击

标签 c++

所以我写了一个代码来模拟游戏中的赌博机。基本上,您按下一个按钮,您就有机会将获得的学分翻倍。另一方面,如果你失败了,你必须重新开始。一个示例运行可能是:

Start of run 1:
0
1
2
Start of run 2:
0
1
Start of run 3:
0
Start of run 4:
0
1
2

它工作正常。我让代码执行一定数量的运行(由用户输入“n”确定)并输出在所有这些运行中达到的最大组合。它还会告诉您何时超过了最高组合。

问题是,在运行一定次数后,无论出于何种原因,最高连击都不能超过 15。从字面上看,每次我输入 1000 万或更多 (,它都会给出 15。考虑到它与概率根本不匹配,这似乎不正确。

我播种的方式有问题吗?

#include <iostream>
#include <stdlib.h>
//#include "stdafx.h"
#include<ctime>

using namespace std;

int main() {

    int n = 1;

    srand(time(0));
    while (n > 0) {
        cin >> n;

        int highestCombo = 0;
        for (int i = 0; i < n; i++) {
            int combo = 0;
            while (true) {
                int r = (rand() % 2) + 1;

                if (r == 1) {
                    combo++;
                }
                else if (r == 2) {
                    if (combo > highestCombo) {
                        highestCombo = combo;
                        cout << combo << " at #" << i << endl;
                    }
                    combo = 0;
                    break;
                }
            }
        }
        cout << "Highest Combo: " << highestCombo << endl;
    }
}

编辑:看来它可能只是我的 IDE。诡异的。我正在使用 Dev-C++,因为我只是想快速编写它。但是,cpp.sh 超过 15 并进入 20s。

最佳答案

正确答案似乎来自 tobi303。我为您测试了他的解决方案,使用“<随机>”效果更好。

#include <iostream>
#include <stdlib.h>
//#include "stdafx.h"
#include<ctime>

using namespace std;

int main() {

int n = 1;

//srand(time(NULL));

std::mt19937 rng;
rng.seed(std::random_device()());
std::uniform_int_distribution<std::mt19937::result_type> rand(1,2); 
while (n > 0) {
    cin >> n;

    int highestCombo = 0;
    for (int i = 0; i < n; i++) {
        int combo = 0;
        while (true) {
            //int r = (rand() % 2);
            int r = rand(rng);

            if (r == 1) {
                combo++;
            }
            else if (r == 2) {
                if (combo > highestCombo) {
                    highestCombo = combo;
                    cout << combo << " at #" << i << endl;
                }
                combo = 0;
                break;
            }
        }
        if(i == n - 1)
        {
            cout << " i " << i << endl;
        }
    }

    cout << "Highest Combo: " << highestCombo << endl;
}

关于c++ - "Double or Nothing"赌博机代码无法超过15连击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43344317/

相关文章:

c++ - TripleDes 会改变数据大小吗

c++ - 为两个类之间具有循环依赖关系定义重载转换运算符

c++ - 如何使用MVP在OpenGL中绘制椭圆

c++ - 提升 vector 序列化追加问题

c++ - 多重集 STL 无法识别的查找函数

c++ - 如何一劳永逸地在VS中设置配置属性?

c++ - 如何知道 double 变量中是否存在 NAN 值?

c++ - 用圆形和三角形设计形状类

c++ - 宏 `assert` ,为什么它不能在全局范围内编译?

c++ - 合并排序链表