C ++ Проблемы генерации новых случайных чисел в цикле / при запросе - PullRequest
0 голосов
/ 27 мая 2018

Я почти закончил эту базовую программу для игры в кости, но не могу понять, что я сделал не так для srand.Предполагается случайным образом бросить 2 кубика для пользователя, и у них есть возможность оставить то, что они бросили (K) или снова бросить (R).Я хотел бы, чтобы программа выводила новые «случайные» числа для броска костей каждый раз, когда пользователь вводит «R», когда его спрашивают, хотят ли они бросить снова, но те же цифры продолжают отображаться.

ОстальныеПрограмма, кажется, работает хорошо - пользователь играет против компьютера.Как мне сгенерировать новые числа для roll1 и roll2, когда пользователь вводит «R», когда его просят сохранить или перекатить?

#include <stdlib.h> /// need this for srand() -- for random numbers
#include <time.h> /// need this for time() -- time
#include <iostream>  /// need this for cout<< and cin>>
using namespace std; /// need this for cout<< and cin>>

int main()
{
    int iseed = (int)time(0);
    srand(iseed);

    cout << "Beat the computer! \n";

    int roll1 = 1+rand()%6; /// make a random number for die # 1 for user
    int roll2 = 1+rand()%6; /// make a random number for die # 2 for user
    int UserRoll = roll1 + roll2; /// totals the sum of die 1 and die 2 for the user
    char keep;

    do
    {
    cout << "You rolled a " << roll1 << " and a " << roll2 << " for a total of: " << UserRoll << "\n";
    cout << "\n";

        do
        {
        cout << "Would you like to keep this total, or roll again? \n";
        cout << "\n";
        cout << "Enter \"K\" for keep and \"R\" for roll again: \n";
        cin >> keep;

            if (keep != 'K' && keep != 'R')

            {
                cout << "That is not a valid choice. Please choose Y to keep your total or N to roll again. " << endl;
                cout << "\n";
            }

            } while(keep != 'K' && keep != 'R');



            if (keep == 'R')
            {
                cout << "You chose R--let's roll again. \n";
            }


            else
            {
            cout << "Great! Your total is " << UserRoll << "\n";
            }
        } while (keep == 'R');

    int roll3 = 1+rand()%6; /// make a random number for die # 1 for computer
    int roll4 = 1+rand()%6; /// make a random number for die # 2 for computer
    int ComputerRoll = roll3 + roll4; /// totals the sum of die 1 and die 2 for the computer


    cout << "The computer rolled a " << roll3 << " and a " << roll4 << " for a total of: " << ComputerRoll << "\n";
    cout << "\n";

    if (ComputerRoll < UserRoll)
    {
        cout << "Congratulations! You won! \n";
    }

    if (ComputerRoll > UserRoll)
    {
        cout << "Sorry. You lose. \n";
    }

    if (ComputerRoll == UserRoll)
    {
        cout << "It's a tie. \n";
    }

return 0;
}

/*
SAMPLE RUNS:
------------
Beat the computer!
You rolled a 4 and a 6 for a total of: 10

Would you like to keep this total, or roll again?

Enter "K" for keep and "R" for roll again:
R
You chose R--let's roll again.
You rolled a 4 and a 6 for a total of: 10

Would you like to keep this total, or roll again?

Enter "K" for keep and "R" for roll again:
K
Great! Your total is 10
The computer rolled a 4 and a 6 for a total of: 10

It's a tie.

Process returned 0 (0x0)   execution time : 8.763 s
Press any key to continue.

*/

Ответы [ 2 ]

0 голосов
/ 27 мая 2018

Отлично!У меня наконец есть рабочая программа!Кто-нибудь, дайте мне знать, если вы думаете, что есть способ, которым я могу сделать это аккуратнее и легче читать:

#include <stdlib.h> /// need this for srand() -- for random numbers
#include <time.h> /// need this for time() -- time
#include <iostream>  /// need this for cout<< and cin>>
using namespace std; /// need this for cout<< and cin>>


int roll1,roll2,UserRoll;
char keep;

void roll()
    {
        roll1 = 1+rand()%6; /// make a random number for die # 1 for user
        roll2 = 1+rand()%6; /// make a random number for die # 2 for user
        UserRoll = roll1 + roll2; /// totals the sum of die 1 and die 2 for the user
    }

int main()
{
    int iseed = (int)time(0);
    srand(iseed);

    cout << "Beat the computer! \n";

    roll();

    do
    {
    cout << "You rolled a " << roll1 << " and a " << roll2 << " for a total of: " << UserRoll << "\n";
    cout << "\n";

        do
        {
        cout << "Would you like to keep this total, or roll again? \n";
        cout << "\n";
        cout << "Enter \"K\" for keep and \"R\" for roll again: \n";
        cin >> keep;

            if (keep != 'K' && keep != 'R')

            {
                cout << "That is not a valid choice. Please choose Y to keep your total or N to roll again. " << endl;
                cout << "\n";
            }

            } while(keep != 'K' && keep != 'R');



            if (keep == 'R')
            {
                cout << "You chose R--let's roll again. \n";
                roll();
            }


            else
            {
            cout << "Great! Your total is " << UserRoll << "\n";
            }
        } while (keep == 'R');

    int roll3 = 1+rand()%6; /// make a random number for die # 1 for computer
    int roll4 = 1+rand()%6; /// make a random number for die # 2 for computer
    int ComputerRoll = roll3 + roll4; /// totals the sum of die 1 and die 2 for the computer


    cout << "The computer rolled a " << roll3 << " and a " << roll4 << " for a total of: " << ComputerRoll << "\n";
    cout << "\n";

    if (ComputerRoll < UserRoll)
    {
        cout << "Congratulations! You won! \n";
    }

    if (ComputerRoll > UserRoll)
    {
        cout << "Sorry. You lose. \n";
    }

    if (ComputerRoll == UserRoll)
    {
        cout << "It's a tie. \n";
    }

return 0;
}

/*
SAMPLE RUNS:
------------
Beat the computer!
You rolled a 2 and a 4 for a total of: 6

Would you like to keep this total, or roll again?

Enter "K" for keep and "R" for roll again:
R
You chose R--let's roll again.
You rolled a 4 and a 4 for a total of: 8

Would you like to keep this total, or roll again?

Enter "K" for keep and "R" for roll again:
R
You chose R--let's roll again.
You rolled a 4 and a 1 for a total of: 5

Would you like to keep this total, or roll again?

Enter "K" for keep and "R" for roll again:
R
You chose R--let's roll again.
You rolled a 5 and a 5 for a total of: 10

Would you like to keep this total, or roll again?

Enter "K" for keep and "R" for roll again:
R
You chose R--let's roll again.
You rolled a 6 and a 1 for a total of: 7

Would you like to keep this total, or roll again?

Enter "K" for keep and "R" for roll again:
R
You chose R--let's roll again.
You rolled a 5 and a 2 for a total of: 7

Would you like to keep this total, or roll again?

Enter "K" for keep and "R" for roll again:
R
You chose R--let's roll again.
You rolled a 6 and a 6 for a total of: 12

Would you like to keep this total, or roll again?

Enter "K" for keep and "R" for roll again:
K
Great! Your total is 12
The computer rolled a 3 and a 1 for a total of: 4

Congratulations! You won!

Process returned 0 (0x0)   execution time : 19.487 s
Press any key to continue.
*/
0 голосов
/ 27 мая 2018

Вы катитесь только один раз и снова используете результат этого броска.если пользователь нажмете R еще раз.это должно катиться снова, чтобы обновить новые числа.ради этого просто добавьте

void roll(){
    roll1 = 1+rand()%6; /// make a random number for die # 1 for user
   roll2 = 1+rand()%6; /// make a random number for die # 2 for user
UserRoll = roll1 + roll2; /// totals the sum of die 1 and die 2 for the user

}

Помните: roll1, roll2 и UserRoll должны быть объявлены глобально перед функцией roll ()

непосредственно перед методом main ()и вызовите его, когда пользователь нажмет R, а также после

cout << "Beat the computer! \n";

и удалите его из основного метода.Это все, что вам нужно сделать

...