范围内的随机数(每次运行后的范围变化)

时间:2016-10-28 15:40:15

标签: c++ random

我试图猜测我的号码程序,计算机猜测我选择的号码,我似乎最终得到它的工作除了随机数范围,高数字工作但数字较低没有按' T,

我想我不应该做lowGuess = rand(),但我不知道我应该做什么,有人能指出我正确的方向吗?

也可以随时向我提供有关其余代码的反馈,这是我自己写一些东西的第一次尝试。 (附有一点参考资料)

#include "stdafx.h"
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>

using namespace std;

const int high = 100;
const int low = 1;
int lowGuess = 1;
int highGuess = 100;
int myNumber = 0;
int guess = 0;
int guesses = 0;
bool correct = 0;

int askNumber();
int askResponse();
int guessNumber();

int main()
{
    askNumber();

    do
    {
        guessNumber();
        askResponse();
    } while (correct == 0);
    cout << "Yes!! I guesed your number in " << guesses << " guesses.";

    return 0;
}

int askNumber()
{
    cout << "\n\nEnter a number between " << low << " - " << high << ".\n\n";
    cin >> myNumber;

    if (myNumber < low || myNumber >high)
    {
        return askNumber();
    }
}

int guessNumber()
{
    srand(static_cast<unsigned int>(time(0)));
    lowGuess = rand();                              //im   doing something wrong here with lowGuess
    guess = (lowGuess % highGuess) + 1;             //im trying to generate a random number between
    cout << "\n\nMy guess is " << guess << endl;    //the value of lowGuess and highGuess
    guesses += 1;                                   //highGuess is working as intended but lowGuess isn't

    //printing values to see them working
    cout << "low " << lowGuess << " high " << highGuess << endl;

    return 0;
}

int askResponse()
{
    int response;
    cout << "\n\nIs my guess too high, too low, or correct?\n\n";
    cout << "1. Too High.\n";
    cout << "2. Too Low.\n";
    cout << "3. Correct.\n\n";

    cin >> response;
    if (response < 1 || response > 3)
    {
        return askResponse();
    }
    else if (response == 1)
    {
        cout << "\n\nToo high eh? I'll take another guess.\n\n";
        highGuess = guess;              //altering the upper limit of random number range
    }
    else if (response == 2)
    {
        cout << "\n\nToo low eh? I'll take another guess.\n\n";
        lowGuess = guess;               //alteing the lower limit of random number range
    }
    else if (response == 3)
    {
        correct = 1;
    }

    return 0;
}

2 个答案:

答案 0 :(得分:1)

使用C ++ 11中的<random>,您可以执行以下操作:

int guessNumber(int low, int high, std::mt19937& eng)
{
    std::uniform_int_distribution<int> uniform_dist(low, high);

    auto guess = uniform_dist(eng);
    std::cout << "My guess is " << guess << std::endl;
    return guess;
}

Demo

答案 1 :(得分:-1)

srand只应调用一次,通常在main。如果您每次使用相同的种子致电srand,则下一个rand()将始终相同。

guessNumber功能更改为

int guessNumber()
{
    guess = lowGuess + rand() % (highGuess - lowGuess);
    cout << "\n\nMy guess is " << guess << endl;    
    guesses += 1;                                   
    cout << "low " << lowGuess << " high " << highGuess << endl;
    return 0;
}

例如20 + rand() % 50将生成0到20到70之间的数字。