C++根据行数列数左上右上右下坐标获取
时间: 2023-05-25 18:04:50 浏览: 84
在C语言中,可以使用二维数组来表示矩阵,并通过下标来访问元素。因此,可以根据行数列数左上右上右下坐标获取一个元素的值。
下面是一个示例代码:
```c
#include <stdio.h>
int main()
{
int ROWS = 3; // 行数
int COLS = 3; // 列数
int matrix[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // 二维数组表示矩阵
int row = 1; // 元素所在行数
int col = 1; // 元素所在列数
int topLeft = matrix[0][0]; // 左上角元素
int topRight = matrix[0][COLS-1]; // 右上角元素
int bottomRight = matrix[ROWS-1][COLS-1]; // 右下角元素
int element = matrix[row][col]; // 获取元素值
// 输出结果
printf("Matrix:\n");
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
printf("Element at row %d, col %d: %d\n", row, col, element);
printf("Top left: %d\nTop right: %d\nBottom right: %d\n", topLeft, topRight, bottomRight);
return 0;
}
```
输出结果:
```
Matrix:
1 2 3
4 5 6
7 8 9
Element at row 1, col 1: 5
Top left: 1
Top right: 3
Bottom right: 9
```