【问题标题】:rand function not "defined"rand 函数未“定义”
【发布时间】:2016-11-19 23:32:35
【问题描述】:

我目前正在使用 Visual Studio 在 C++ 中编写我的第一个游戏(Snake),我试图在屏幕上的随机区域设置你吃的块但是当我使用 rand() 函数时它说它是未定义的,确实有谁知道我为什么会出现这个错误?

#include <iostream>
using namespace std;
bool gameOver;
const int WIDTH = 20;
const int HEIGHT = 20;
int x, y, foodX, foodY, score;
enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN};
eDirection dir;
void Setup(){
    gameOver = false;
    dir = STOP;
    x = WIDTH /2;
    y = HEIGHT /2;
    //rand function below is not defined??
    //I thought the function was built in

    foodX = rand() % WIDTH;
    foodY = rand() % HEIGHT;

}

void Draw() {

}
void Input() {


}
void Logic() {


}
int main()
{
    Setup();
    while (!gameOver)
    {
        Draw();
        Input();
        Logic();
    }


    return 0;
}

【问题讨论】:

    标签: c++ function random


    【解决方案1】:

    你缺少一个包含

    #include &lt;cstdlib&gt;

    http://www.cplusplus.com/reference/cstdlib/rand/

    【讨论】:

      【解决方案2】:

      rand 定义在标题 cstdlib 中,因此您需要添加此包含:

      #include <cstdlib>
      

      【讨论】:

      • rand() 在库代码中定义,您通常无法访问。 std::rand() 在标题cstdlib声明rand() 在标题stdlib.h声明
      • 对我之前评论的澄清:编译器抱怨 name rand 没有定义。这是正确的。我的观点是关于 函数 rand(),它在标题中声明并在库代码中定义。
      猜你喜欢
      • 2017-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-08
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2014-10-01
      相关资源
      最近更新 更多