| | |
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. I'm here to prove you wrong.
![]() |
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 |
api array arrays based beginner binary c++ c/c++ calculator char class classes code compile compiler console conversion count delete deploy desktop directshow dll download dynamic dynamiccharacterarray encryption error file forms fstream function functions game getline givemetehcodez google graph gui homeworkhelp homeworkhelper iamthwee ifstream input int integer java lib linkedlist linker linux list loop looping loops map math matrix memory news number output parameter pointer problem program programming project proxy python random read recursion recursive reference return rpg string strings struct temperature template templates test text text-file tree unix url variable vector video visual visualstudio win32 windows winsock word wordfrequency wxwidgets






