rand函数没有“已定义”

时间:2016-07-17 06:07:24

标签: c++ function random

我目前正在使用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;
}

2 个答案:

答案 0 :(得分:3)

您错过了包含

#include <cstdlib>

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

答案 1 :(得分:1)

标头rand中定义了

cstdlib,因此您需要添加以下内容:

#include <cstdlib>