随机数有问题

having trouble in random numbers

本文关键字:有问题 随机数      更新时间:2023-10-16

该程序生成随机数并让用户猜测。我正在使用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;
   }
}

你缺少 cstdlib 的包含。这是一个最小的工作示例:

#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
    // your code goes here
    std::cout<<rand()<<std::endl;
    return 0;
}