rand() Function

closed account (oEwqX9L8)
I'm working on an assignment for a beginner C++ course. We are creating a program to play "Plinko."

Part of the program requires generating a random number between 0 and 8. I think I have accomplished that part with this line of code

cout << rand() % 9 << endl;

The program is required to take input between 0 and 8 then generate a random number starting at that the input and never deviating by more than 0.5.

ex)
Input = 3
Output = 3.5, 4.0, 4.5, 5.0, 4.5, 5.0, 5.5, 5.0, etc.

I am pretty lost on how to accomplish this part (and the rand() function in general really).

Can anyone point me in the right direction? Thanks!
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <random>

int main()
{
    int n = 3 ;
    
    std::cout << std::fixed << std::setprecision(2) ;

    // legacy: generate ten random numbers within n - 0.5 and n + 0.5
    std::srand( std::time(nullptr) ) ;
    
    for( int i = 0 ; i < 10 ; ++i )
    {
        const double r = std::rand() / double(RAND_MAX) ; // random number in [ 0.0, 1.0 ]
        const double delta = r - 0.5 ; // random number in [ -0.5, +0.5 ]
        std::cout << n + delta << ' ' ;
    }
    std::cout << '\n' ;

    // C++11: generate ten random numbers within n - 0.5 and n + 0.5
    std::mt19937 rng( std::random_device{}() ) ;
    std::uniform_real_distribution<double> distrib( -0.5, +0.5 ) ;
    
    for( int i = 0 ; i < 10 ; ++i )
    {
        const double delta = distrib(rng) ; // random number in [ -0.5, +0.5 ]
        std::cout << n + delta << ' ' ;
    }
    std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/f3f5bac41be28be4
Topic archived. No new replies allowed.