c++ - Object initialized with random numbers -
i'm pretty new c++ , oo, pretty silly. in code right after include statements.
enum objtype { cube, cone, }; typedef struct { objtype type; float x; float y; float z; int selected; } object; static object objects[] = { { cube, rand()%11-4, rand()%-10-5, rand()%-65-55, 0}, { cone, rand()%11-4, rand()%-10-5, rand()%-65-55, 0}, }
i make call srand, passing in current time, in main method. however, generating same random numbers every time program wrong. not understanding?
as zenith says, initialization of globals happens before main()
. srand()
run first doing declaring global variable initialization calls srand()
, , comes before initialization of static object objects[]
:
static int x = (srand(time(null)), 10); static object objects[] = { { cube, rand()%11-4, rand()%-10-5, rand()%-65-55, 0}, { cone, rand()%11-4, rand()%-10-5, rand()%-65-55, 0}, };
but global variables bad idea anyway, , relying on things initialization order (which specified between objects initialized in same translation unit) particularly bad.
instead use local variables:
int main() { srand(time(null)); object objects[] = { { cube, rand()%11-4, rand()%-10-5, rand()%-65-55, 0}, { cone, rand()%11-4, rand()%-10-5, rand()%-65-55, 0}, }; // pass objects around needed foo(objects[0]); foo(objects[1]); }
the c++ standard library provides facilities superior srand()
, rand()
, , manually transforming results generate particular distributions. use header <random>
, create , seed generator such std::mt19937
using random_device
instead of time(null)
, , use distribution objects:
#include <random> int main() { std::random_device r; std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()}; std::mt19937 eng(seed); std::uniform_int_distribution<> dist; object objects[] = { { cube, dist(eng, {-4, 6}), dist(eng, {-5, 4}), dist(eng, {-55, 9}), 0}, { cone, dist(eng, {-4, 6}), dist(eng, {-5, 4}), dist(eng, {-55, 9}), 0}, }; // pass objects around needed foo(objects[0]); foo(objects[1]); }
note how easier read, right down directly stating desired intervals, rather relying on how %
behaves negative numbers.
(i'm not sure original intervals weren't mistakes, i've faithfully reproduced them assuming common behavior %
negative numbers, wasn't standardized until c++11.)
Comments
Post a Comment