循环数组:While循环和2D数组

时间:2020-07-08 11:08:13

标签: arrays c multidimensional-array while-loop

某些上下文:该程序读取Stone的线条并将其放置在地图上。

程序应首先要求STONE的行数为整数。然后,程序将按照以下格式将行的位置扫描为一组四个整数:

行列长度值

行和列代表在地图上放置的块的水平线的最左边的块。 长度告诉您在该水平线上应有多少块石头。 在此示例中,假定第四个整数始终为1,表示一块石头。

示例:CommandMeaning

0 0 5 1 放置一条从[0] [0]开始到[0] [4]结束的石头线。该行中的所有5个正方形都将设置为1(STONE)。

我尝试在长度方面进行编码的问题,我无法弄清楚模式:

  • 此外,我们只允许使用while循环,不能使用for循环
#define SIZE 15
#define EMPTY 0
#define STONE 1

void printMap(int map[SIZE][SIZE], int playerX);


int main (void) {
    // This line creates our 2D array called "map" and sets all
    // of the blocks in the map to EMPTY.
    int map[SIZE][SIZE] = {EMPTY};


    // This line creates out playerX variable.
    int playerX = SIZE / 2;

    printf("How many lines of stone? ");
    int linesOfStone; 
    scanf("%d", &linesOfStone);

    printf("Enter lines of stone:\n");
 
    int rowPos; 
    int columnPos; 
    int stoneLength; 
    int stoneValue; 
   
    int i = 0; 
    while (i < linesOfStone) {
        scanf("%d %d %d %d", &rowPos, &columnPos, &stoneLength, &stoneValue); 
        map[rowPos][columnPos]++; //pos for position
      
//ERROR: This was my attempt to incorporate the length aspect, i think my logic got lost along the way... 
  
            int j = 0; 
            while (j < stoneLength) {
            rowPos++; 
            j++; 
            }
    i++; 
    }

    printMap(map, playerX);

    return 0;
}

// Print out the contents of the map array. Then print out the player line
// which will depends on the playerX variable.
void printMap(int map[SIZE][SIZE], int playerX) {
    
    // Print values from the map array.
    int i = 0;
    while (i < SIZE) {
        int j = 0;
        while (j < SIZE) {
            printf("%d ", map[i][j]);
            j++;
        }
        printf("\n");
        i++;
    }    
    
    // Print the player line.
    i = 0;
    while (i < player

1 个答案:

答案 0 :(得分:0)

用这个替换第二个while循环:

for (int j=0; j < stoneLength; j++)  // Iterate over all affected map tiles
    map[rowPos + j][columnPos] = 1;  // Make this map tile STONE

这会将所有地图图块设置为从[rowPos][columnPos][rowPos + stoneLength - 1][columnPos]