gpt4 book ai didi

arrays - 格式化和打印二维数组 (VB6)

转载 作者:行者123 更新时间:2023-12-01 23:12:47 25 4
gpt4 key购买 nike

我需要乘法表程序方面的帮助。该程序通过文本框询问用户二维数组的维度。当检索尺寸时,程序应在表格中整齐地打印给定尺寸的乘法表。问题是,我不知道如何以表格格式整齐地打印数组。作为示例输出,它是这样的:

1 2  3  4  5 
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

这是我的工作。

Option Explicit

Dim maxNum As Integer
Dim multiplicationTable() As Integer
Dim x As Integer
Dim y As Integer

Private Sub cmdDisplay_Click()

cmdDisplay.Enabled = False
maxNum = Val(txtDimension.Text)

ReDim multiplicationTable(maxNum, maxNum) As Integer

For y = 1 To maxNum
For x = 1 To maxNum
multiplicationTable(x, y) = x * y
Next x
Next y

End Sub

哪段代码可以使该程序在表单中整齐地打印表格?

最佳答案

这将完全按照您在“整洁”示例中显示的方式打印表格。每列的宽度等于该列中的最大位数(加上一个空格分隔符)。有些人可能认为统一的列宽(=整个表中的最大位数)看起来会更整洁,并且可以轻松修改代码来做到这一点。

' Convert integer table to string table
Dim astrTable() As String
ReDim astrTable(1 To UBound(multiplicationTable, 1), _
1 To UBound(multiplicationTable, 2))
Dim intMaxDigitsInColumn As Integer
Dim intDigitsInThisNumber As Integer
For y = 1 To maxNum
' Determine width of column (= max number of digits)
intMaxDigitsInColumn = 1
For x = 1 To maxNum
intDigitsInThisNumber = 1 + _
Int(Log(multiplicationTable(x, y)) / Log(10#))
If intDigitsInThisNumber > intMaxDigitsInColumn Then
intMaxDigitsInColumn = intDigitsInThisNumber
End If
Next x

' Convert each table element into string of appropriate length
For x = 1 To maxNum
astrTable(x, y) = Space(intDigitsInThisNumber)
Mid(astrTable(x, y), 1) = CStr(multiplicationTable(x, y))
Next x
Next y

' Print the table with a space delimiter between columns
Dim strTable As String
strTable = ""
For x = 1 To maxNum
For y = 1 To maxNum
strTable = strTable & astrTable(x, y) & " "
Next y
strTable = strTable & vbCrLf
Next x
Debug.Print strTable

关于arrays - 格式化和打印二维数组 (VB6),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6968172/

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