+ 1

rand() function

When I use rand function to generate numbers between two numbers but one of them isn't 1, this results in generating numbers out of my range, can anyone explain this to me please?

4th Mar 2017, 1:55 PM
Batman Ever
Batman Ever - avatar
7 Respostas
+ 12
I tried your code and using 5+(rand()%6) works, I'll find out why soon😉
4th Mar 2017, 4:31 PM
C.E.
C.E. - avatar
+ 11
I looked for the answer and found this on stack overflow: http://stackoverflow.com/questions/12657962/how-do-i-generate-a-random-number-between-two-variables-that-i-have-stored Basically int randNum = rand()%(max-min + 1) + min; so 5+(rand()%(10-5+1)) That's why six worked (I just try with smaller numbers until it worked )XD
4th Mar 2017, 4:35 PM
C.E.
C.E. - avatar
+ 9
what's your code?
4th Mar 2017, 2:18 PM
C.E.
C.E. - avatar
+ 3
#include <iostream> #include <random> #include <ctime> using namespace std; int main() { srand(time(0)); int min, max; cin >> min >> max; int a, b; do { a = rand() % (max - min + 1 ) + min); b = rand() % (max - min + 1 ) + min); } while(a != 1 || b != 1); cout << a << ' ' << b; } If you want to learn about your errors, post your code.
4th Mar 2017, 2:34 PM
SUPER_S
SUPER_S - avatar
+ 2
Begin by seeding a random value , by using srand () function . Then use the current time in second by passing time (0) as an argument in the srand () function to obtain different value each time the program is executed : srand ( time ( 0 )) ; Finally use the modulus operator to setup a range of value : outcome = 1 + ( rand () % 6 ) ; // This will generate values between 1 - 6 Note : Add one the expression to avoid obtaining zero's and include the cstdlib header file.
4th Mar 2017, 2:58 PM
handerson scott
handerson scott - avatar
+ 2
Thnak you all guys, I guess the exact right answer for this question is the following syntax: rand()%(max - min + 1) + min thanks Elizabeth Espindola☺
4th Mar 2017, 5:33 PM
Batman Ever
Batman Ever - avatar
0
#include <iostream> #include <cstdlib> using namespace std; int main() { for ( int i=0; i <10; i++) cout<<5+(rand()%10)<<endl; system ("pause"); return 0; } /* outputs: 13 7 15 5 5 13 7 15 7 5 */
4th Mar 2017, 2:33 PM
Batman Ever
Batman Ever - avatar