0
C++ misunderstandings.
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { const short minValue = 1; const short maxValue = 6; srand(time(0)); short first = (rand() % (maxValue - minValue + 1)) + 1; short second = (rand() % (maxValue - minValue + 1)) + 1; cout << first<<", " << second; return 0; } What is the use of these two "+1" in the code below? "(rand() % (maxValue - minValue + 1)) + 1"
1 Odpowiedź
+ 4
Eriito rand()%N returns random number between 0 to N-1 .
rand()%6 means 0 to 5. So that "+1" to include upper limit(6).
Second "+1" was mistake change it to "+minValue" then only you can get random number between min and Max value.
For example assume min=2 max=6
rand()%(maxValue - minValue +1))+minValue
rand()%(6-2+1)+2
rand()%(4)+2
It generates random 'between 0 to 4', then add minValue to increase 0 to the minimum value.
If rand() was 1, 1+2=3 so the output between minValue and maxValue