if statement - C++ need assistance with if != to a random number -


i working on project , stuck. have 2 variables generate random numbers. want check checks make sure variables not same number, , if are, repeat process until not same. here have :

num_enemy = 3;  int f =  rand() % num_enemy; int m =  rand() % num_enemy;  if ( f != m ) { enemy_ptr[f] -> fire_weapon(); enemy_ptr[m] -> update_status(); } 

the code above wont work plus how can make if false generate random numbers again?

i not looking answers, assistance on need do. thanks!

the problem when gets section...

if ( f != m ) {     enemy_ptr[f] -> fire_weapon();     enemy_ptr[m] -> update_status(); } 

... variables f , m have same value, due modulo, fire_weapon() , update_status() functions never called. need loop until both variables have different values. code below should sort out.

const int num_enemy = 3; int f = rand() % num_enemy; int m;  // do-while loop guaranteed called @ least once. {     m = rand() % num_enemy; } while ( f == m ); // repeat loop if values same  // @ point, f , m have different values. enemy_ptr[f] -> fire_weapon(); enemy_ptr[m] -> update_status(); 

because variables modulo low value, it's possible loop may have run many times before f != m.

also, if want sequence of pseudo-random numbers returned rand() different each time game run, seed psuedo-random number generator call srand( time() ) once. if want sequence constant each time run game leave is. can debugging, , required if game needs deterministic.

read more rand() , srand() here: http://www.cplusplus.com/reference/cstdlib/rand/

as mentioned in answer, c++11 has improved random number generation. find out more here: http://www.cplusplus.com/reference/random/


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -