Re: WHy my program doesn't work
Erik Wikstr?m wrote:
#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
srand(time(0));
unsigned int nr = static_cast<unsigned int>(1000000000 *
rand() / double(RAND_MAX)
I don't think that will work. Assuming that the largest value is about
4Gib, you will overflow most of the data that rand() outputs when
multiplying it by 1000000000, loosing most of your resolution. The
following should work:
unsigned int nr = static_cast<unsigned int>(
(rand() * rand()) % 1000000000)
Assuming that RAND_MAX*RAND_MAX >= 1000000000-1 (in actual math, not on
a CPU's integer arithmetic set) this should work. And although (rand()
* rand()) could overflow, it wouldn't matter as that information is not
needed when trying to get a value in the range [0, 1000000000).
);
std::cout << nr;
return 0;
}
Adrian
--
_____________________________________________________________________
\/Adrian_Hawryluk BSc. - Specialties: UML, OOPD, Real-Time Systems\/
\ _---_ Q. What are you doing here? _---_ /
\ / | A. Just surf'n the net, teaching and | \ /
\__/___\___ learning, learning and teaching. You?_____/___\__/
\/______[blog:__http://adrians-musings.blogspot.com/]______\/