【问题标题】:Displaying 2d array as a map将二维数组显示为地图
【发布时间】:2014-12-06 06:16:46
【问题描述】:

我需要一个二维数组来显示为地图。 g_length 和 w_width 是从 x 和 y 点开始的长度。需要创建一个循环,该循环需要放置在地图上的作物的宽度和长度。x_crop 和 y_crop 是应该创建作物的 x 和 y 坐标。 w_width 是宽度,g_length 是类中作物的长度或高度。

bool Crop::place(char map[MAPL][MAPW],int x_crop,int y_crop)const{

int y_total =y_crop;
y_total = y_crop + g_length;

for(int x=0; x < MAPW;x++){

    if(x==x_crop){
        for(int b=0; b < w_width;b++){
            if(y_total==y_crop){
                map[x][y_crop] = PlantType.symbol();
                x++;
                y_crop++;
            }else{
                b=w_width;
            }   
        x++;        
        }
    }
}


cout << '\n';
cout << setw(24) << right << "11111111112\n";
cout << setw(24) << right << "12345678901234567890\n";
cout << "  " << setw(21) << setfill('-') << left << '+' << right << '+' << setfill (' ') << endl;



for(int x=0; x < MAPW;x++){
    cout << setw(2) << right << x+1 << "|";
    for(int y=0; y < MAPL;y++){
        cout << map[x][y];

    }
    cout << "|" << endl;
}

cout << "  " << setw(21) << setfill('-') << left << '+' << right << '+' << setfill (' ') << endl;
cout << setw(24) << right << "11111111112\n";
cout << setw(24) << right << "12345678901234567890\n";

return true;}

输出应该是这样的:

            11111111112
   12345678901234567890
  +--------------------+
 1|                    |
 2|                    |
 3|    cc              |
 4|    cc              |
 5|    cc              |
 6|    cc              |
 7|           pppppppp |
 8|           pppppppp |
 9|           pppppppp |
10|                    |
  +--------------------+
            11111111112
   12345678901234567890

>

【问题讨论】:

  • 问题是什么?
  • @Jarod42 for 循环应该如何获得问题中提供的输出?

标签: c++ arrays class object multidimensional-array


【解决方案1】:

不要让循环过于复杂:

for (int x = x_crop; x < x_crop + w_width; ++x) {
    for (int y = y_crop; y < y_crop + g_height; ++y) {
        map[x][y] = PlantType.symbol();
    }   
}

一些补充说明:

  • 您可能需要考虑添加对参数 x_cropy_crop 的检查,以保持在地图范围内
  • 使您的代码中的地图索引保持一致,在循环中您通过map[x][y] 对其进行索引,但参数声明char map[MAPL][MAPW] 建议它应该由map[y][x] 进行索引

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-29
    • 2011-02-28
    • 2021-12-28
    • 1970-01-01
    相关资源
    最近更新 更多