Home > Enterprise >  How do I use the rand functions output in C ?
How do I use the rand functions output in C ?

Time:09-04

I am trying to create a slot machine where I have to generate 3 random numbers from 2 - 7 and then use that output to give different outcomes. For example if the output is 777 and then your bet gets multiplied by 10, if it's 222 then it gets multiplied by 5. I can't seem to get the output of the rand function into a variable to use it and its not calculating properly.

Code:

This is not the full code

if (bet <= 2000)
    {
        std::cout << endl;

        int game_num = 0;
        srand (0);
        for (int i = 0; i < 3; i  )
        std::cout << (rand() % 1)   2;
        std::cout << endl;

        if (game_num == 777)
        {
            bet = bet * 10;
            std::cout << "You Won: " << bet << endl;
            return 0;
        }

        else if (game_num == 222 || 333 || 444 || 555 || 666)
        {
            bet = bet * 5;
            std::cout << "You Won: " << bet << endl;
            return 0;
        }

CodePudding user response:

The issue is that you aren’t seeding the random number generator properly in this situation.

This will always return the same sequence of random numbers every time the program runs.

srand(0)

You want to seed the random number generator with a new value each time the program is run.

Using the timestamp at runtime will enable that behavior.

srand(time(0))

CodePudding user response:

Dan's answer is correct, you're using the same seed every time, so every sequence of numbers is identical. You need to seed with a random value. Time as source of randomness isn't great in terms of being random, but it's working unless you run twice in the same second (due to time() only counting seconds, and seconds being ... long for modern computers, unlike 1970's computers, when that way of seeding was invented).

So, instead, honestly, don't use srand or rand at all. They're really bad random number generators to begin with, and their dependence on "hidden" state makes them a nightmare to deal with. Simply. Ignore their existence!

C brings its own random facilities:

You want a uniform integer distribution, so use uniform_int_distribution. Seed with an actual random value from actual randomness-generating events.

#include <random>

// … 
// Somewhen before you need the random numbers, not every time:

    // Will be used to obtain a seed for the random number engine
    std::random_device real_random;  
    // Set up the generator for random bits, seed it from the actual random 
    std::mt19937 gen(real_random());
    // Use that to generate random numbers in [2,7]
    std::uniform_int_distribution<> distrib(2, 7);

// Where you need the randomness:
    for (int i = 0; i < 3; i  )
        std::cout << distrib(gen) << "\n";
  • Related