0

Problem with Rand function

i wrote this code to make a dice game , but i'm facing problems with the rand function i want the random number to be between 0 and 5 to fit my array (1 to 6) #include <iostream> #include <string> #include <ctime> #include <cstdlib> using namespace std; int main() { srand(time(NULL)); int arr[] = {1,2,3,4,5,6} ; int signed num; int r=1; while (r==1) { num= (rand() %5 ) ; cout << "Rolling The dice BY Mohamed Jarmouni" << endl; cout << "\n \n Your dice fell on the number : " << arr[num] << " side" << endl; cout << "\n \n Do you wanna replay ? \n 1-For (yes) \n 2-For (no)" << endl; cin >> r; } return.0; } when i execute it i get sometimes get some weird numbers like 71564896 and i can't get the number 6

15th Dec 2018, 9:23 PM
SIMO
SIMO - avatar
2 Respuestas
+ 4
rand() % 5 will produce numbers between 0 and 4, so you will only get the numbers 1 to 5. You need to replace it with rand() % 6. I don't know why you get weird numbers, this usually happens when you try to access the tenth element of an array that only has five elements or so. But I don't see how this would happen in your code.
15th Dec 2018, 9:42 PM
Anna
Anna - avatar
+ 1
Thanks ! That helped to get the six number . I tried to run this code on a phone compiler cxxdroid and i didn't get those weird numbers . Maybe it's a problem with code blocks
15th Dec 2018, 9:56 PM
SIMO
SIMO - avatar