繁体   English   中英

将数据填充到二维数组中

[英]filling data in a 2d array

我正在尝试用C ++制作战舰游戏。 我正在做的是尝试确定船舶位置的起点和终点,然后程序将填补空白以完成船舶。 int size部分是告诉程序哪艘船在那里。 例如。 小型,中型或大型船。 由于某种原因,我不明白为什么这行不通

int fill(int arr[10][10], int x1, int y1, int x2, int y2, int size){

    if(x1 == x2){
        if(y1 > y2){
            for(int i = y2; i < y1; i++){arr[x1][i] = size;}
        }

        else{
            for(int i = y1; i <= y2; i++){arr[x1][i] = size;}
        }
    }
    else if(y1 == y2){
        if(x1 > x2){
            for(int i = x2; i < x1; i++){arr[y1][i] = size;}
        }
        else{for(int i = x1; i <= x2; i++){arr[y1][i] = size;}}
    }
    return arr;

}

当我传递变量x1 = 4, y1 = 4, x2 = 6, y2 = 4, size = 3 ,它不会填补空白,并且起点/终点之间的空间仍然为空。

我的完整代码可以在这里找到: https : //repl.it/@SakshamGoyal/project它仍在进行中,因此会有很多冗余代码

如果只需要填写数组,则可以使方法的返回类型为void 除此之外,您的代码还可以:

void fill(int arr[10][10], int x1, int y1, int x2, int y2, int size) {
    if (x1 == x2) {
        if (y1 > y2) {
            for (int i = y2; i < y1; i++) {
                arr[x1][i] = size;
            }
        } else {
            for (int i = y1; i <= y2; i++) {
                arr[x1][i] = size;
            }
        }
    } else if (y1 == y2) {
        if (x1 > x2) {
            for (int i = x2; i < x1; i++) {
                arr[y1][i] = size;
            }
        } else {
            for (int i = x1; i <= x2; i++) {
                arr[y1][i] = size;
            }
        }
    }
}

void fillZero(int a[10][10]) {
    for (int i = 0; i < 10; i++)
        for (int j = 0; j < 10; j++)
            a[i][j] = 0;
}

int main() {
    int a[10][10];
    fillZero(a);
    fill(a, 2, 1, 5, 1, 2);
    // Print array:
    for (auto &i : a) {
        for (int j : i)
            cout << j << " ";
        cout << endl;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM