输入4×4的数组,编写程序实现:(1)求出对角线上各元素的和; (2)求出对角线上行、列下标均为偶数的
来源:学生作业帮助网 编辑:作业帮 时间:2024/11/19 05:58:49
输入4×4的数组,编写程序实现:(1)求出对角线上各元素的和; (2)求出对角线上行、列下标均为偶数的
输入4×4的数组,编写程序实现:(1)求出对角线上各元素的和; (2)求出对角线上行、列下标均为偶数的
输入4×4的数组,编写程序实现:(1)求出对角线上各元素的和; (2)求出对角线上行、列下标均为偶数的
#include <iostream>
#include <string>
#define M 4
#define N 4
using namespace std;
int main (int argc, char** argv) {
int i, j, sum1, sum2;
sum1 = sum2 = 0;
int array[M][N] = {0};
cout << "请给数组赋值初始化: ";
for (i = 0; i < M; ++i) {
for (j = 0; j < N; ++j) {
cin >> array[i][j];
}
}
cout << "赋值完成" << endl;
for (i = 0; i < M; ++i) {
for (j = 0; j < N; ++j) {
cout << array[i][j] << " ";
}
cout << endl;
}
cout << sum1 << " " << sum2 << endl;
//对角线求和
for (i = 0; i < M; ++i) {
for (j = 0; j < N; ++j) {
if (i == j) {
sum1 += array[i][j];
//对角线上均为偶数的元素和
if (0 == i % 2) {
sum2 += array[i][j];
}
}
}
}
cout << "对角线求和:" << sum1 << endl;
cout << "对角线偶求和:" << sum2 << endl;
return true;
}