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.
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
Here is a simple way to fix the code.
Put a
clock()
in an infinitewhile
loop and let the clock count so that when it reaches two seconds, it triggersrand()
to generate a new random number. Reset theclock()
. Repeat infinitely.Now the Math behind:
As you already know, delta time is the final time, minus the original time.
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
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
isCLOCKS_PER_SEC
. Now delta time isAnd when
deltaTime > secondsToDelay
, you generate a new random number.Putting all that into code results in this:
Say
t
is the current time in seconds (time(0)
). It is obvious thatt
changes once per second. Thent/2
, because of rounding, changes every two seconds.