在数组中移动碎片?C

Moving pieces in an array? C++

本文关键字:碎片 移动 数组      更新时间:2023-10-16

您如何移动数组字符??????????????

这是一些带有高级注释的基本代码。它是并不完全按照您的要求。但是,由于您提供了一些代码,因此几乎存在。

阅读评论并了解正在发生的事情后,根据您的要求将以下代码修改为相对简单:

#include <iostream>
void printArray(int gameboard[5][5]){
  std::cout << "This is what the gameboard looks like now:"  << std::endl;
  for ( int i = 0; i < 5; i++ ) {
    for ( int j = 0; j < 5; j++ ) {
       std::cout << gameboard[i][j] << ' ';
    }
    std::cout << std::endl;
  }
}
int main() {
  // Declare array and print what it looks like
  int gameboard[5][5] = { {1,2,3,4,5}, {1,2,3,4,5}, {1,2,3,4,5}, {1,2,3,4,5}, {1,2,3,4,5}};
  printArray(gameboard);
  // Get input for which coordinates the user wants to swap
  int row1, column1, row2, column2;
  std::cout << "Please enter the coordinates of the first piece:" << std::endl;
  std::cout << "Row:";
  std::cin >> row1;
  std::cout << "Column:";
  std::cin >> column1;
  std::cout << "Please enter the coordinates of the second piece:" << std::endl;
  std::cout << "Row:";
  std::cin >> row2;
  std::cout << "Column:";
  std::cin >> column2;
  // Swap values at provided coordinates by using a temp variable
  int temp = gameboard[row1][column1];
  gameboard[row1][column1] = gameboard[row2][column2];
  gameboard[row2][column2] = temp;
  printArray(gameboard);
  return 0;
}

示例用法:

This is what the gameboard looks like now:
1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 
Please enter the coordinates of the first piece:
Row: 0
Column: 0
Please enter the coordinates of the second piece:
Row: 4
Column: 4
This is what the gameboard looks like now:
5 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 1 

为您做任务:

  • 更改printArray以允许尺寸的数组不仅是5 x 5
  • 确保用户输入rowcolumn和值是数字。
  • 确保用户输入row,并且column值在数组的边界内。