I cant make this dice game to work


I want to make a dice game in which when the number generator rolls six the loop stops, but it goes forever.I'm new in C++ and im on 13 so dont judje me

#include <iostream>
#include <string>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;


int main(){
srand(time(0));
int timesr = 0;
while(numofd <= 6){
int numofd = rand()%7;
cout << "You rolled " << numofd << endl;
timesr++;
}
cout << "It took " << timesr << "rolls to get a six" << endl;


}

I want to make a dice game in which when the number generator rolls six the loop stops, but it goes forever.I'm new in C++ and im on 13 so dont judje me
Last edited on
while(numofd <= 6)

It sounds like you want the loop to keep running while the number rolled (numofd) is not equal to 6 (numofd != 6), instead of less than or equal to 6.

rand()%7 will return a number 0 through 6, so right now, the loop condition numofd <= 6 is always going to be true. If you mean to have a random number 1 through 6 instead of 0 through 6, that rand line needs a little tweaking.

Edit: I would also pull the declaration of int numofd outside of the loop.
Last edited on
Ok i changed it to while (numofd != 6) but the loop keeps runnig. I moved the int otside the loop, too.I see when the program says You rolled 6, but it doesn't stop.Also, I made the number generator to be 1+(rand()%6) so it doesnt say you rolled 0,too.
Last edited on
This seems to work. (I also assigned an initial value to numofd of 0.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main(){
    
    srand(time(0));
    int timesr = 0;
    int numofd = 0;
    while(numofd != 6){
        numofd = 1+(rand()%6);
        cout << "You rolled " << numofd << endl;
        timesr++;
    }
    cout << "It took " << timesr << " rolls to get a six" << endl;
    
    return 0;
}
You rolled 3
You rolled 5
You rolled 1
You rolled 3
You rolled 6
It took 5 rolls to get a six
Thanks it worked.I rewrote the program and it runs smoothly.
Last edited on
Topic archived. No new replies allowed.