나는 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
각 숫자 끝에 추가 했지만 도움이되지 않았습니다. 여전히 정의되지 않은 (?) 동작이 나타납니다. 내가 뭘 잘못하고 있습니까?
int rnd = rand() % (sizeof(gRandomPlayerSpawns));
이 줄은 잘못되었습니다. 이 배열에 sizeof를 적용하면 4 * 3 * sizeof (float)가 (내 컴퓨터에서) 48이됩니다. float는 4 바이트의 메모리를 사용하기 때문입니다. sizeof (float)로 나눈 경우에도 [0, 4 [] 범위를 예상하는 다음 계산에 대해 범위를 벗어난 12를 얻을 수 있습니다.
대체 접근 방식을 제안 할 수있는 경우 :
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] 삭제
몇 마디 만하겠습니다