I'm looking to create a timer that counts down from a random amount of time.
Basically the timer should be set to a random amount of time in a certain time frame, and count down from that time to zero. I've been trying to understand how all the things in the time.h work, but it doesn't stick in my head. Here's what I have so far:
It would help if you gave an example of how this was to be used. The interface isn't intuitive to me.
What are your trying to accomplish in Timer::countdown()? The total_time ( the value returned) is almost always going to be zero because the amount of time from setting running_time to setting total_time will be measured in nanoseconds (significantly less that CLOCKS_PER_SEC).
Do you need to count in seconds? If so, just iterate downwards through a loop, using sleep(1) each iteration, which will cause your application to sleep for a second.
Here is a sample application with comments which will hopefully help you understand:
#include <iostream>
#include <cassert>
#include <ctime>
int main()
{
int min;
std::cout << "enter min time value (in s): ";
std::cin >> min;
int max;
std::cout << "enter max time value (in s): ";
std::cin >> max;
assert(max > min);
// seed random number generator with current time
srand(time(NULL));
// get a random number, and ensure it fits within the specified time window
int num = rand() % (max - min) + min;
// count down to zero, displaying the time left and then sleeping for a second
while (num > 0)
{
std::cout << num-- << std::endl;
sleep(1);
}
return 0;
}
I'll try to run that. I just have a little bit of difficulty understanding why we take the modulus of the division of a random number by (max - min) and then add it to min.