C++ School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become a C++ Expert!

Join 300,480 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,765 people online right now. Registration is fast and FREE... Join Now!




Generating random Number in an interval

 

Generating random Number in an interval

m.babanfati

3 Jul, 2009 - 01:37 AM
Post #1

New D.I.C Head
*

Joined: 10 Dec, 2007
Posts: 23


My Contributions
Hello All;

I want to generate a random number (integer) between 15 and 30; and after consulting several tutorials on random number generation, I learnt I can do what I want by simply executing the following code

CODE

cout << rand() % 30 + 15;


Although most of the times, I get a number within the range; but to my surprise, many at times I get a value above the limit (outside the interval), like say 41, 39, 32, 33 and so on.

please how can I do away with this problem.


User is offlineProfile CardPM
+Quote Post


venkateshps

RE: Generating Random Number In An Interval

3 Jul, 2009 - 02:45 AM
Post #2

New D.I.C Head
*

Joined: 24 Mar, 2009
Posts: 44



Thanked: 3 times
My Contributions
The statement you have written will generate numbers between 15 to 45.
User is offlineProfile CardPM
+Quote Post

venkateshps

RE: Generating Random Number In An Interval

3 Jul, 2009 - 02:57 AM
Post #3

New D.I.C Head
*

Joined: 24 Mar, 2009
Posts: 44



Thanked: 3 times
My Contributions
try this

int t=rand() % 30;

if (t<=15)
cout<<t+ 15<<endl;
else
cout<<t<<endl;

User is offlineProfile CardPM
+Quote Post

m.babanfati

RE: Generating Random Number In An Interval

3 Jul, 2009 - 03:02 AM
Post #4

New D.I.C Head
*

Joined: 10 Dec, 2007
Posts: 23


My Contributions
Thank you for clarifying what my output will always be. I now got the logic and solved the problem

thanks once again
User is offlineProfile CardPM
+Quote Post

ComputerAnalysis

RE: Generating Random Number In An Interval

3 Jul, 2009 - 11:51 AM
Post #5

D.I.C Head
**

Joined: 29 Jun, 2009
Posts: 72



Thanked: 5 times
My Contributions
Better yet the following code accomplishes the same task and is more efficient because no check is required.

CODE

int t = rand() % 16 + 15


This will generate pseudo-random within the range of 15 to 30 without a check.
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic

Time is now: 11/8/09 03:46AM

Live C++ Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month