我正在给C++写一个脚本,我遇到了一些大问题。
我定义了一个带值的浮动数组(这是一个非常短的数组,我的实际数组有100k个元素)如下:
float gRandomPlayerSpawns[4][3] = {
{2194.7808,1024.5272,79.5547},
{2099.8562,1158.2679,11.6484},
{1953.1841,1342.9954,15.3746},
{2000.6274,1519.7140,17.0625}
};现在,当我执行以下代码时:
void SetPlayerRandomSpawn(int playerid)
{
int rnd = rand() % (sizeof(gRandomPlayerSpawns));
ServerLog::Print(playerid,-1,Functions::string_format(
"Setting position to: %f %f %f",
gRandomPlayerSpawns[rnd][0], gRandomPlayerSpawns[rnd][1], gRandomPlayerSpawns[rnd][2]).c_str());
SetPlayerPos(playerid, gRandomPlayerSpawns[rnd][0], gRandomPlayerSpawns[rnd][1], gRandomPlayerSpawns[rnd][2]); // Warp the player
SetPlayerFacingAngle(playerid, 45.0);
}我永远不会得到数组中的任何值..总是奇怪的值,或者0,0,0,或者类似这样的东西:
Setting position to: 283969270356831250000000000000.000000 18523600588218255000000000000.000000 72697250258806125000000000000000.000000或#INF:00000 / infinity等。
我还使用了上面发布的数组,并将f添加到每个数字的末尾,但它没有帮助,我仍然得到未定义的(?)行为,我做错了什么?
发布于 2013-07-06 09:39:23
int rnd = rand() % (sizeof(gRandomPlayerSpawns));这条线是错的。将sizeof应用于此数组将得到4*3* sizeof( float ),这是(在我的机器上) 48,因为一个float占用4个字节的内存。即使你除以sizeof(浮点数),你仍然会得到12,这对于你的后续计算来说是超出范围的,因为你期望的范围是[0,4]。
如果我可以推荐另一种方法:
struct PlayerSpawn {
float x, y, z;
};
// There may be a slighting cleaner way of doing this.
std::vector<PlayerSpawn> spawnsLocations;
{
PlayerSpawn spawns[4] = { {2194.7808,1024.5272,79.5547},
{2099.8562,1158.2679,11.6484},
{1953.1841,1342.9954,15.3746},
{2000.6274,1519.7140,17.0625}
};
std::copy(&spawns[0], &spawns[4], std::vector<PlayerSpawn>::emplace_back);
} // The static array will go out of scope here, it's somewhat of a needless optimization though
int rand = 0 % spawnsLocations.size(); // call rand here instead of 0, size of the vector should be 4 here但实际上,您可以直接使用push_back将值添加到向量中,或者使用特定的大小(例如4)初始化数组,然后将值分配给每个索引(从0到3)。由你决定。
https://stackoverflow.com/questions/17498772
复制相似问题