gpt4 book ai didi

c++ - 矩阵c++对角线元素之和

转载 作者:行者123 更新时间:2023-11-30 00:42:39 31 4
gpt4 key购买 nike

我想找到用户使用此代码定义的矩阵对角线之和,它适用于主对角线但不适用于次对角线,我不明白问题出在哪里。任何帮助将不胜感激。

#include <iostream>
using namespace std;

int main() {
int r, c, j,i,k,sum1,sum2;
cout << "Enter the size of matrix: ";
cin >> j;
int matrix[j][j];

for (r = 0; r < j; r++) {
for (c = 0; c < j; c++) {
cout << "matrix" << "[" << r << "]" << "[" << c << "] = ";
cin >> matrix[r][c];
}
}
cout << "\n";

for ( i = 0; i < j; i++) {
for ( k = 0; k < j; k++) {
cout << " "<<matrix[i][k] << " ";
}
cout << "\n";
}

cout<<"\n";

cout<<"Main diagonal is: ";
for( i=0;i<j;i++){
cout<<matrix[i][i];
}
cout<<"\n";


for( i=0;i<j;i++){
sum1=sum1+matrix[i][i];}
cout<<"Sum of the elements of main diagonal is: "<<sum1;
cout<<"\n";
cout<<"\n";

cout<<"Secondary diagonal is: ";
for(i=0,k=j-1;i<j;i++,k--){
cout<<matrix[i][k];
}


for(i=0,k=j-1;i<j;i++,k--){
sum2=sum2+matrix[i][k];
}

cout<<"Sum of the elements of secondary diagonal is: "<<sum2;
return 0;
}

最佳答案

对于初学者来说,可变长度数组不是标准的 C++ 功能。请改用类模板 std::vector

例如

std::vector<std::vector<int>> matrix( j, std::vector<int>( j ) );

或者至少像动态分配数组一样

int **matrix = new int *[j];
for ( i = 0; i < j; i++ ) matrix[i] = new int[j];

在这种情况下,您应该在退出程序之前释放所有分配的内存

for ( i = 0; i < j; i++ ) delete [] matrix[i];
delete [] matrix;

其次,sum1 和 sum2 都没有被初始化。

int r, c, j,i,k,sum1,sum2;

要计算次对角线的元素之和,您可以这样写

sum2 = 0;
for ( i = 0; i < j; i++ ){
sum2 += matrix[i][j - i - 1];
}

关于c++ - 矩阵c++对角线元素之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58839577/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com