填充对角线以使每一行、列和对角线的和等于 3×3 矩阵,使用 c++
假设我们有一个 3x3 矩阵,其对角线元素最初为空。我们必须填充对角线,使行、列和对角线的和相等。假设一个矩阵如下所示 -

填充后,如下所示 -

假设对角线元素为 x、y、z。这些值如下 -
- x = (M[2, 3] + M[3, 2])/ 2
- z = (M[1, 2] + M[2, 1])/ 2
- y = (x + z)/2
示例
#include<iostream>
using namespace std;
void displayMatrix(int matrix[3][3]) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
cout << matrix[i][j] << " ";
cout << endl;
}
}
void fillDiagonal(int matrix[3][3]) {
matrix[0][0] = (matrix[1][2] + matrix[2][1]) / 2;
matrix[2][2] = (matrix[0][1] + matrix[1][0]) / 2;
matrix[1][1] = (matrix[0][0] + matrix[2][2]) / 2;
cout << "Final Matrix" << endl;
displayMatrix(matrix);
}
int main() {
int matrix[3][3] = {
{ 0, 3, 6 },
{ 5, 0, 5 },
{ 4, 7, 0 }};
cout << "Given Matrix" << endl;
displayMatrix(matrix);
fillDiagonal(matrix);
}输出
Given Matrix 0 3 6 5 0 5 4 7 0 Final Matrix 6 3 6 5 5 5 4 7 4
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP