计算矩阵之和的方法取决于具体的需求。以下是几种常见情况的代码示例:
计算整个矩阵的元素之和
```cpp
include using namespace std; int main() { int n, i, j, sum = 0; cout << "Enter the dimension n: "; cin >> n; int p = new int*[n]; for (i = 0; i < n; i++) { p[i] = new int[n]; cout << "Enter elements of row " << i + 1 << ": "; for (j = 0; j < n; j++) { cin >> p[i][j]; sum += p[i][j]; } } cout << "Sum of all elements in the matrix: " << sum << endl; // Remember to delete the allocated memory for (i = 0; i < n; i++) { delete[] p[i]; } delete[] p; return 0; } ``` ```cpp include using namespace std; int main() { int m, n, s, i, a = 0, c = 0; cout << "Enter m and n: "; cin >> m >> n; int sum; // Assuming a maximum of 100 rows cout << "Enter "<< m << " * "<< n << " matrix: "; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { cin >> s; a += s; if (j == n - 1) { sum[c++] = a; a = 0; } } } for (i = 0; i < m; i++) { cout << "Sum of row " << i + 1 << ": " << sum[i] << endl; } return 0; } ``` ```cpp include using namespace std; int main() { int m, n, i, j, sum = 0; cout << "Enter m and n: "; cin >> m >> n; int a; // Assuming a maximum of 6x6 matrix cout << "Enter elements of matrix: "; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { cin >> a[i][j]; sum += a[i][j]; } } cout << "Sum of all elements in the matrix: " << sum << endl; return 0; } ``` ```cpp include using namespace std; int main() { int k, m, n, i, j, sum, t; cout << "Enter the number of test cases: "; cin >> k; while (k > 0) { cout << "Enter m and n: "; cin >> m >> n; sum = 0; for (i = 1; i <= m; i++) { for (j = 1; j <= n; j++) { cin >> t; if (i == 1 || i == m || j == 1 || j == n) { sum += t; } } } cout << "Sum of edge elements: " << sum << endl; k--; } return 0; } ``` 根据你的具体需求,可以选择合适的代码示例进行相应的修改和扩展。计算矩阵各行元素之和
计算矩阵各列元素之和
计算矩阵边缘元素之和