简体   繁体   English

打印出2D数组,替换值

[英]Printing out 2D Array, replacing the values

it's my first time using arrays and I'm stuck on this. 这是我第一次使用数组而且我坚持这个。 How can I change the values inside a 2D array and print it out? 如何更改2D数组中的值并将其打印出来?

For example, I want to replace the 1s with " 例如,我想用“替换1” " (space) and the 2s with " * " and then print them out. How can i do that? “(空格)和带有” * “的2s然后打印出来。我怎么能这样做?

This is my code: 这是我的代码:

#include <iostream>

using namespace std;

int main(){

    int Xshape[5][5] = {{2,1,1,1,2},
                        {1,2,1,2,1},
                        {1,1,2,1,1},
                        {1,2,1,2,1},
                        {2,1,1,1,2},

    };
    {
        for (int row = 0; row<5 ; row++)
        for (int column=0; column < 5; column++)
        {
            cout << Xshape[row][column] << endl;
        }

    }
    system("pause");

}

i think it has something to do with the if-else statement but i cant pull it off can someone help me please? 我认为它与if-else声明有关但我无法将它拉下来有人可以帮我吗?

Yes, it can be done with a simple if-statement: 是的,可以使用简单的if语句完成:

for (int column=0; column < 5; column++)
{
    int val = Xshape[row][column];
    if (val == 1){
        cout << " " << endl;
    }else if (val == 2){
        cout << "*" << endl;
    }else{
        //  Handle error case of neither 0 nor 1.
    }
}

我不确定这是不是你的意思,但你可以用以下方式改变它:Xshape [row] [col] = value;

something like this: 这样的事情:

for (int column=0; column < 5; column++)
{
  switch (Xshape[row][column])
  {
    case 1: cout << " " << endl;
            break;
    case 2: cout << "*" << endl;
            break;

    default:assert(0); 
            break;
  }
}
for (int row = 0; row<5 ; row++)
  { 
  for (int column=0; column < 5; column++)
   {
    if(Xshape[row][column]==1) cout << " ";
    else if(Xshape[row][column]==2) cout << "*";
   }
     cout << "\n";
  }

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

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