如何更改int以使其具有较小的字段来选择随机数

时间:2017-07-10 16:14:56

标签: c++

//Computer Guess My nUmber Game

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main()
{
    srand(static_cast<unsigned int>(time(0))); //randomizer
    int computerguess = rand() %100+1;
    int attempts=0;
    int useranswer;
    cout<<"Guess My Number Game \n\n";
    cout<<"Enter your secretnumber\n";
    cin>>useranswer;
    do
    {
        cout<<"I guess its "<<computerguess<<endl;
        ++attempts;
        if (useranswer<computerguess)
        {
            cout<<"Ur answer is too high mr.Computer\n";
            int computerguess = rand() %100+1;                  //need help here
        }
        else if(useranswer>computerguess)
        {
            cout<<"Ur answer is too low mr.Computer\n";
            int computerguess = rand() %100+1;                 // and here
        }
        else
        {
            cout<<"CORRECT MR COMPUTER! You won in "<<attempts<<" attempts\n";
        }
    } while (useranswer!=computerguess);

    return 0;
}

我只是需要它来使随机数发生器选择的数字区域变小?

1 个答案:

答案 0 :(得分:2)

您可以通过将“%100”更改为“%10”来缩小范围,其中10是您想要的数字范围。

基本上,rand()生成一个介于0和(至少)32767之间的随机数。“%”是模数,它会在您将当前代码中的此随机数除以100之后找到剩余的余数。因此,如果您碰巧随机获得32767,则32767/100为327,剩余67个。因此,32767%100是67.由于modulo可以导致零,你可能想要一个整数,你加一个所以范围从0-99(因为如果你除以100就不能有100个剩余)到1-100。