You are here:

C++/rand() in C++

Advertisement


Question
How can I use rand() to generate values between 100 and 500?
I have been trying the following:
x=rand()% 500 + 100;
but it gives values larger than 500.
I am using Microsoft Visual C++ 6.0 on Win XP.
Thanks

Answer
Hello Mohamad, thank you for the question.

If you rand() % 500, it could produce 497 for instance. Then you add 100 to it and you have 597. There is an algorithm for doing a rand() between a high and a low number. Here it is in a helper function:

int RandomNumber(int high, int low)
{
return ((rand() % high - low) + low + 1);
}

This should produce the desired results you want every single time.

I hope this information was helpful.

- Eddie

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 About.com. All rights reserved.