Can someone help me write this program?

closed account (4wRjE3v7)
This is my code so far, but I know it's not correct, can someone give me helpful tips thank you!P.S I have to use a for loop.
-Michelle

I have to write a program that roles a single die using the random generator until a five is rolled. The program should count the number of rolls that were taken before the five was rolled an output this number at the end.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <ctime>
using namespace std;

int main()
{
    srand((unsigned)time(NULL));

    int i=0,secret,num,roles=0;
    secret = rand() % 6 + 1;
    
    for(i; i<20; i++)
    {cout << "Welcome to the role the dice game\n";
    cout << "Please press any number to start the role ";
    cin >> num;
        if(secret!=5)
        { roles++;
        }
        if(num==secret && secret==5)
        {
            cout<<"The dice rolled" << roles << "times before rolling 5.";
            return 0;
        }
    }
    
  
}


Last edited on
There are a couple of issues here. First off, why do you loop to 20 here for(i; i<20; i++)? I would take everything out of that for-loop, and instead do a while-loop after
1
2
cout << "Please press any number to start the role ";
    cin >> num;
, which would look something like while(secret != 5). Inside that loop I would then do secret = (rand()%6) + 1; to actually "roll the dice"
closed account (4wRjE3v7)
@fafner but the assignment does not allow me to use a while loop
Aha, I did not read your post properly:P

This is what I would do:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <cstdlib>
#include <iostream>
#include <ctime>

int main()
{
    srand((unsigned)time(NULL));

    int i=0,secret,num,roles=0;
    
    std::cout << "Welcome to the role the dice game\n";
    
    for(i; i<20; i++) {
    std::cout << "Please press any number to start the role ";
    std::cin >> num;
    secret = rand() % 6 + 1;
        if(secret!=5)
        { roles++;
        }
        else
        {
            std::cout<<"The dice rolled" << roles << "times before rolling 5.";
            return 0;
        }
    }
    std::cout << "The dice did not roll 5 once.\n";
  
}
closed account (4wRjE3v7)
@fafner thanks! But would I need to output secret or say if number =secret ? Or something similar?? Thanks for your help
I'm not sure I understand what you mean. The code I gave you does what the assignment asks for, it shouldn't be necessary to print anything else.
Topic archived. No new replies allowed.