Need help with simple code.

closed account (N0M9z8AR)
Roll two dice repeatedly until you roll the same total value twice in a row. State how many times it took.

I don't know what to put inside the while to stop after two in a row.

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
29
30
31
32
33
34
35


#include <iostream>
#include <time.h>
#include <stdlib.h>

using namespace std;

int main()
{


    int dice1, dice2, counter = 0;
    srand(time(NULL));

    do{

        dice1 = rand()%6+1;
        dice2 = rand()%6+1;

        cout << dice1 << " " << dice2 << " = " << dice1+dice2<<endl;
        counter++;



    }while();

    cout << "It took: " << counter << " tries";




    return 0;
}
you need to store value of your lastRoll and compare it to your currentRoll. So you while loop should be while(lastRoll != currentRoll)

Also a do while loop does not seem to work well here. just using a while loop is easier. Let me know if you'd like me to explain the code further.

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
29
30
31
32
33
34
#include <iostream>
#include <time.h>
#include <stdlib.h>

using namespace std;

int main()
{


    int dice1, dice2, lastRoll = 666, counter = 0, totalRoll = 333;
    srand(time(NULL));

    while(lastRoll!=totalRoll)
    {   dice1 = rand()%6+1;
        dice2 = rand()%6+1;
        totalRoll = dice1 + dice2;

        cout << dice1 << "+" << dice2 << " = " << totalRoll <<endl;
        counter++;
        if(lastRoll!=totalRoll)
        {
            lastRoll = totalRoll;
            totalRoll = 333;
        }
    }

    cout << "It took: " << counter << " tries";




    return 0;
}
Last edited on
closed account (N0M9z8AR)
Thank you for helping me, the one thing I don't understand is why the totalRoll and lastRoll is equal to 333 and 666?
Last edited on
You're Welcome! And totalRoll = 333 just to initialize it into a value i can use to identify errors. It could be 0 as long as it does not equal the initialized value of lastRoll or else the while loop wont execute.

Ohhh totalRoll in line 24 is set to 333 because if i didn't change the value totalRoll would equal lastRoll making the while statement true even though the dice were not rolled twice in a row.
Last edited on
closed account (N0M9z8AR)
I see, thank you very much
Hope i explained it well enough. I should have used a bool for the while statement to make it easier to read! Lol my apologies.
Topic archived. No new replies allowed.