Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'rand' function in C++?

I'm trying to make a death predictor that has a random chance for your character to die as your progress. I'm going to make it have multiple chances to die as well as higher chances the older you grow. How do I fix this basic rand function, to make it so int RandomFactor has a 1-20 number and activates randomly to kill you (sorry if this sounds sadistic)?

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <Windows.h>
#include <stdlib.h>
#include <time.h>

using namespace std;

int main() {
    srand(time(NULL));
    int RandomFactor;
    RandomFactor = rand();
    20 % 1;

    for (double count = 0; count < 20; count++) {
        if (count < 20) {
            Sleep(360);
            cout << "\n\t\t\tIt's your birthday! You turned: " << count;
        } 
        else
            if (RandomFactor == 1) {
                cout << "\n\n\n\t\t\tBANG! You're dead!";
            }
    }

    cout << "\n\n\n\t\t\t  ";

    return 0;
}
like image 419
Chantola Avatar asked Feb 14 '26 08:02

Chantola


1 Answers

You can use rand % 20 but it won't be truly uniform, it will contain bias. Your better option in C++ is to use std::uniform_int_distribution<> this way

#include <random>
#include <iostream>

int main()
{
    std::random_device rd;
    std::mt19937 gen( rd());
    std::uniform_int_distribution<> dis( 1, 20);

    for ( int n=0; n<10; ++n)
        std::cout << dis(gen) << ' ';
    std::cout << '\n';
}

You can read this to learn more about the bias introduced by rand() % x.

like image 100
4pie0 Avatar answered Feb 15 '26 22:02

4pie0