| | |
rand() range help
Please support our C++ advertiser: Intel Parallel Studio Home
![]() |
•
•
Join Date: Nov 2007
Posts: 16
Reputation:
Solved Threads: 1
C++ Syntax (Toggle Plain Text)
<span class="ad_notxt"><code class="inlinecode"> int high=10; int low=6; rand () % (high - low + 1) + low; </code></span>
hope that helps.
•
•
•
•
C++ Syntax (Toggle Plain Text)
<span class="ad_notxt"><code class="inlinecode"> int high=10; int low=6; rand () % (high - low + 1) + low; </code></span>
I was hoping some one could shed some light on the reason this works. I have used rand() in the past to simulate rolling dice (1-100 etc.). I have never used the minimum number like this. why is it that rand() % 11 = a range of 6 - 10?
Thank you!
>I was hoping some one could shed some light on the reason this works.
Think of it as a normal range shifted to fit your lower bound. When you use x % y, it forces x to be within the range of 0 to y. This corresponds to
Think of it as a normal range shifted to fit your lower bound. When you use x % y, it forces x to be within the range of 0 to y. This corresponds to
rand() % ( high - low + 1 ) , or rand() % 5 . So now you have a number from 0 to 5 (excluding 5), but you really want a number from 6 to 11 (excluding 11). So you add the lowest number in your range, which is 6. This effectively shifts the range to what you want by changing the normal lower bound to the lower bound that you want. New members chased away this month: 3
![]() |
Similar Threads
- Helping with calling a function (C)
- random number (C++)
- How to put the random integer between 1-100 into the 2 dimensions array (5x5 metrix) (C++)
- Dont kNow Where this is going wrong?? (C)
- Algorithm Efficiency Help!!!! (C)
- Errors with membering functions in a class (C++)
- please help ASAP!! (C++)
Other Threads in the C++ Forum
- Previous Thread: New in C++ Help with Arrays
- Next Thread: convert integer to array of character???
| Thread Tools | Search this Thread |
Tag cloud for C++
api application array arrays based beginner binary c++ c/c++ calculator char char* class classes code coding compile compiler console conversion convert count data database delete deploy developer display dll dynamiccharacterarray email encryption error file format forms fstream function functions game generator givemetehcodez graph homeworkhelp iamthwee ifstream image input int java lib list loop looping loops map math matrix memory multiple newbie news number numbertoword output pointer problem program programming project python random read recursion recursive reference return rpg simple sorting spoonfeeding string strings struct template templates text tree url variable vector video visual visualstudio void win32 windows winsock wordfrequency wxwidgets






