兰德函数不"defined"

rand function not "defined"

本文关键字:defined 函数      更新时间:2023-10-16

我目前正在使用 Visual Studio 用 c++ 编写我的第一个游戏(贪吃蛇),我正在尝试在屏幕上的随机区域设置你吃的块,但是当我使用 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;
}

您缺少包含

#include <cstdlib>

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

> rand 是在标头cstdlib中定义的,因此您需要添加以下内容:

#include <cstdlib>