因此,我試圖在大約640,000點的區域內生成5個隨機座標,每個座標軸的值在100和900之間。這些座標之間的距離必須大於100,以防止重疊。有搜索以前的答案,並試圖一塊下面的代碼:以它們之間的差異生成隨機座標
struct point
{
int x;
int y;
};
point pointarray[6];
srand (time(NULL));
pointarray[1].x = 100+(std::rand()% 801);
pointarray[1].y = 100+(std::rand()% 801);
for (int n=2; n <= 5 ; n++)
{
double dist;
int currentx;
int currenty;
double xch;
double ych;
while (dist < 100)
{
srand (time(NULL));
currentx = (100+(std::rand()% 801));
currenty = (100+(std::rand()% 801));
xch = (currentx - (pointarray[(n-1)].x));
ych = (currenty - (pointarray[(n-1)].y));
dist = sqrt(xch*xch + ych*ych);
if (dist >= 100 && dist <= 800)
{
currentx = pointarray[n].x;
currenty = pointarray[n].y;
}
}
}
我不明白爲什麼最後4分是絕對龐大的數字(以百萬計),而只有第一個是在要求的範圍之內?
數組索引從0開始,和DIST沒有初始化因此可能while循環永遠不會執行。 –
另外,在'while'循環中調用'srand'可能不會做你想做的事 - 在兩個循環之前調用它應該足夠了。 – Hulk