Generate a Random number every 2 seconds? C++ Sran

2019-06-14 13:01发布

I am studying C++ in order to make a game and I was able to generate a random number every second using the functions of srand. But I wanted the number to be different every 2 second instead.

标签: c++ random
2条回答
小情绪 Triste *
2楼-- · 2019-06-14 13:35

enter image description here

Here is a simple way to fix the code.

Put a clock() in an infinite while loop and let the clock count so that when it reaches two seconds, it triggers rand() to generate a new random number. Reset the clock(). Repeat infinitely.

Now the Math behind:

As you already know, delta time is the final time, minus the original time.

dt = t - t0

This delta time, though, is simply the amount of time that passes while in the while loop.

The derivative of a function represents an infinitesimal change in the function with respect to one of its variables. Our deltaTime.

The derivative of a function with respect to the variable is defined as http://mathworld.wolfram.com/Derivative.html

                f(x + h) - f(x)
f'(x) = lim    -----------------
        h->0           h

First you get a time, i.e TimeZero = clock() , for reference.

Then you subtract that time from a new time you just got and devide it by h. h is CLOCKS_PER_SEC. Now delta time is

deltaTime = (clock() - TimeZero) / CLOCKS_PER_SEC;

And when deltaTime > secondsToDelay, you generate a new random number.

Putting all that into code results in this:

#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;

int main(int argc, char *argv[]){
    cout << "Generate a new random number every 2 seconds \n\n";

    // create a clock and start timer
    clock_t TimeZero = clock(); //Start timer

    double deltaTime = 0;
    double secondsToDelay = 2;
    bool exit = false;

    // generate random seed using time 
    srand(time(0)); 

    while(!exit) {

        // get delta time in seconds
        deltaTime = (clock() - TimeZero) / CLOCKS_PER_SEC;
        cout << "\b" << secondsToDelay - deltaTime << "\b";

         // compare if delta time is 2 or more seconds
        if(deltaTime > secondsToDelay){
            cout << "                      ";

            // generate new random number
            int i = rand() % 100 + 1; 
            cout << "\nNew random : " << i << "           \n"; 

            //reset the clock timers
            deltaTime = clock();
            TimeZero = clock();
        }
      }

    return 0;
}
查看更多
forever°为你锁心
3楼-- · 2019-06-14 13:36

Say t is the current time in seconds (time(0)). It is obvious that t changes once per second. Then t/2, because of rounding, changes every two seconds.

查看更多
登录 后发表回答