c ++ - 随机数有问题

时间:2017-03-30 12:15:10

标签: c++ random

该程序生成随机数并让用户猜测。 我使用Geany作为IDE,它突出显示为错误: 错误消息:error: 'rand' was not declared in this scope

the_number = rand() % 101 + 1;

代码(不工作):

#include <iostream>
using namespace std;
int main()

{
using namespace std;

int the_number;
int guess;
int tries=8;

the_number = rand() % 101 + 1;

cout << "Let's play a game!";
cout << "I will think of a number 1-100. Try to guess it.";
cout << endl;
cin >> guess;

for (tries = 8; tries++;)
{
    if (guess == 8)
    {
        cout << "You guessed it!";
        cout << "And it only took you: "<< tries;
    }
    else if (guess < the_number)
    {
        cout << "Higher";
        tries++;
    }


    else if (guess > the_number)
    {
        cout << "Lower";
        tries++;
    }

    else
         cout << "That's not even in range!";
    return 0;
   }
}

1 个答案:

答案 0 :(得分:2)

您缺少cstdlib的include。这是一个最小的工作示例:

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
    // your code goes here
    std::cout<<rand()<<std::endl;
    return 0;
}