【加试题】求矩阵主对角线元素之和。主对角线是矩阵左上角与右下角所对的直线。程序要求如下:
⑴用户通过输入n,点击按钮Command2生成规模为n×n的数字矩阵;
⑵矩阵元素随机生成,并按数组顺序保存,如规模为3×3的矩阵,元素对应数组的排列方式如图a所示;
⑶点击按钮Command1后输出主对角线上的元素以及其元素之和。
程序界面如图b所示,程序代码如下:
Dim a(100)As Integer,n As Integer
Private Sub Command1_Click() ‘输出主对角线数据及其之和
Dim i As Integer,j As Integer,t As Integer,sum As Integer
t=1:sum=0
For i=1 To n
For i= 1 To n
If ① Then
List2.AddItem Str(a(t))
sum=sum+a(t)
End If
Next i
②
Next i
List2.Addltem“和: ”+Str(sum)
End Sub
Private Sub Command2_Click() ‘生成数组矩阵
Dim i As Integer,s As String
n=Val(Text1.Text) ‘获取矩阵规模
List1.Clear:List2.Clear
Randomize
For i=1 To n2
a(i)=99-Int(Rnd*90)
s=s+Str(a(i))
If ③ Then
List1.AddItem s
s=“”
End If
Next i
End Sub