Jump to content
  • Advertisement
Sign in to follow this  
MAGIgullorks

C++ Help! rand() question...

This topic is 3179 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Alright, Im making an Rpg, and Im using namespaces for the enemies. But whenever I tried using the rand function, it always said 5 in cout. I tried it two different ways, and wondered if you could use variables in a rand() % function: namespace nSlime { int iHealth = 6; int iAttack = 2; int iDefense = 2; int iDrop = 3; } void c() { system("cls"); int iHit = rand() % iAttack; cout << iHit << endl; //-------says 5... return; } //I even tried this too... namespace nSlime { int iHealth = rand() % 6; int iAttack = 2; int iDefense = 2; int iDrop = 3; } void c() { system("cls"); int iHit = iHealth; cout << iHit << endl; //-------Still says 5... return; }

Share this post


Link to post
Share on other sites
Advertisement
first, not sure why you are using the namespaces like that...you should probably be using classes to represent your slime. look into using classes for that.

as for the rand() situation....at the beginning of your program make a call to srand(NULL); dont just use that blindly, google srand and see why you want to call it once at the beginning of the program.

Share this post


Link to post
Share on other sites
The reason is that rand() is a psuedo random number generator. This means that the rand() gives a sequence of numbers that look convincingly random for a given "seed", or initial state. Unless you specify a differet seed, it will always give the same sequence of numbers.

You can seed the rand() generator with srand(). A good candidate for a seed is the return value of the time(NULL) function, which will give you a different number every time you run your program.

Finally, it pays to note that rand() behaving in this way can actually be an advantage. Having a determinstic generator can make it easier to reproduce bugs, which would otherwise change every time the program is run.

Share this post


Link to post
Share on other sites
Thanks for the help, fixed it! This is a simple test for now, and as for Namespace being a Class, I tried it earlier but failed. So i just decided to use this for now, after this game is done I will learn more about classes. But yeah, its not a complex game, so it works fine anyway.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!