编写程序,计算下面4*4二维数组的两条对角线上的元素之和

45 30 26 4855 20 17 3941 25 19 2231 18 22 10 搞错区了,我想问VB
2024-12-04 12:55:45
推荐回答(3个)
回答1:

#include

void main()
{
int a[4][4]={45,30,26,48,
55,20,17,39,
41,25,19,22,
31,18,22,10};
int i,j,sum;
sum = 0;
for(i=0;i<4;i++)
for(j=0;j<4;j++)
{
if(i==j || i+j==3)
sum = sum+a[i][j];
}
printf("%d\n",sum);

}

VB
Private Sub Command1_Click()
Dim a(1 To 4, 1 To 4) As Integer
Dim i As Integer, j As Inreger, sum As Integer
a(1, 1) = 45
a(1, 2) = 30
a(1, 3) = 26
a(1, 4) = 48
a(2, 1) = 55
a(2, 2) = 20
a(2, 3) = 17
a(2, 4) = 39
a(3, 1) = 41
a(3, 2) = 25
a(3, 3) = 19
a(3, 4) = 22
a(4, 1) = 31
a(4, 2) = 18
a(4, 3) = 22
a(4, 4) = 10
sum = 0
For i = 1 To 4
For j = 1 To 4
If i = j Then sum = sum + a(i, j)
Next j
Next i
For i = 1 To 4
For j = 1 To 4
If i + j = 5 Then sum = sum + a(i, j)
Next j
Next i
Print sum
End Sub

回答2:

#include
int main()
{
int i, j, sum;
int angs[4][4];

printf("请输入矩阵:\n");
sum = 0;
for(i = 0; i < 4; i++)
for(j = 0; j < 4; j++)
{
scanf("%d", &angs[i][j]);
if(i == j || i+j == 3)
sum += angs[i][j];
}
printf("%d\n", sum);
return 0;
}

回答3:

VB的
Private Sub Form_Click()

Dim a(3) As Variant

a(0) = Array(45, 30, 26, 48)
a(1) = Array(55, 20, 17, 39)
a(2) = Array(41, 25, 19, 22)
a(3) = Array(31, 18, 22, 10)
Dim sum1 As Integer
sum1 = 0
Dim i, j As Integer

For i = 0 To 3
sum1 = sum1 + a(i)(i) + a(i)(3 - i)
Next i

Print "左上-右下对角线的数之和为:"; sum1

End Sub