无法从C ++中的多维数组检索正确的浮点值

小发明

我正在使用C ++编写脚本,但是遇到了一些大问题。

我定义了一个带有值的float数组(这是一个很短的数组,我的实际数组是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 /无限等。

我还使用了上面发布的数组,并将其添加f到每个数字的末尾,但这并没有帮助,我仍然会出现undefined(?)行为,我在做什么错呢?

宝格丽德
int rnd = rand() % (sizeof(gRandomPlayerSpawns));

这条线是错误的。将sizeof应用于此数组将为您提供4 * 3 * sizeof(float)(在我的机器上为48),因为float占用4个字节的内存。即使您用sizeof(float)除,您仍然会得到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)。由你决定。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章