簡體   English   中英

我正在嘗試將隨機整數分配給struct成員,但無法正常工作

[英]I'm trying to assign random integers to struct members, but it doesn't work properly

我正在做一項作業,我必須將球員隨機放置在具有隨機坐標的場上,但是這些坐標必須唯一,否則必須重新生成。 我正在嘗試將整數隨機化並將其分配給struct成員。 但是,根據我的教授,我現在正在做的事情似乎無法正常工作。 這是結構:

struct player {

   int x;
   int y;
   int direction;
   int id;
   int presence;
};

這是我的兩個數組,一個數組用於該字段,另一個數組用於該字段上的團隊規模:

 int field [25][25];
 struct player team [25];

這是函數中我可能會犯錯的部分:

int main (){

   int i;
   int j;
   int randx, randy;
   int SIZE_TEAM = 25;


   srand (time(NULL));

    for (i = 0; i < SIZE_TEAM; i++){

       randx = (rand () % 25); <-- Randomizing row position
       randy = (rand () % 25); <-- Randomizing column position

       while (field[randx][randy] != 0){ <-- While loop occurs if position in field is taken.
            randx = (rand () % 25);      <-- In this case, the coordinates are regenerated.
            randy = (rand () % 25);
       }
     team [i].x = randx; <--Where the mistake might lie
     team [i].y = randy; <--Where the mistake might lie
     team [i].id = i + 1;
     team [i].presence = 1;
     field [team [i].x][team [i].y] = team [i].id; <--Where the mistake might lie
  }

將它們分配給相關播放器后,我不確定如何“鎖定”隨機生成的值。 您認為我為球員分配位置的算法不正確嗎?

另外,這是我發布的另一個問題的精簡版,但是這個問題太長了,沒有人願意幫助我。

好吧---我不確定這是否是問題的真正原因---但我注意到一個問題:

您不會在字段上初始化場所的值。 所有變量都需要在首次使用它們的值之前進行初始化。 您有一個二維數組,稱為“字段”,其中您假定的每個元素以零開頭---,但您不知道,因為您從未將這些元素設置為零。 您需要一個代碼,在該代碼中,您必須將此二維數組的所有元素設置為它們的初始值, 然后才能開始將玩家放置在場地上。

我可以添加(作為補充)關於此聲明:

int SIZE_TEAM = 25;

而不是在主函數中使其成為整數,而應將其全局聲明為宏-像這樣...

int field [25][25];
#define SIZE_TEAM 25
struct player team [SIZE_TEAM];

這樣,如果您不得不更改團隊規模,則只需在一個地方而不是兩個地方進行更改。

以@WhozCraig建議的方式解決問題實際上並不復雜:

static void random_permutation(int *x, int n)
{
    int i, r;
    /* mark all elements as "unset" */
    for (i = 0; i < n; i++) {
        x[i] = -1;
    }

    for (i = 0; i < n; i++)
    {
        /* start from a random value and find the first unset element */
        for (r = rand() % n; x[r] >= 0; r = (r + 1) % n)
            ;
        x[r] = i;
    }
}

#define SIZE_TEAM 25

int main (void)
{
    int randx[SIZE_TEAM], randy[SIZE_TEAM];
    srand (time(NULL));

    random_permutation(randx, SIZE_TEAM);
    random_permutation(randy, SIZE_TEAM);

    for (i = 0; i < SIZE_TEAM; i++) {
        int x = randx[i], y = randy[i];
        team[i].x = x;
        team[i].y = y;
        team[i].presence = 1;
        team[i].id = i + 1;
        field[x][y] = team[i].id;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM