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

时间:2011-08-06 16:33:12

标签: arrays vb6

我在乘法表程序中需要帮助。程序通过文本框询问用户二维数组的维度。检索维度时,程序应在表单中整齐地打印具有给定维度的乘法表。问题是,我不知道如何以表格格式整齐地打印数组。这是一个样本输出:

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

哪一段代码可以使这个程序在表格中整齐地打印出来?

1 个答案:

答案 0 :(得分:5)

这将完全按照您在“整洁”示例中显示的方式打印表格。每列的宽度等于该列中的最大位数(加上一个空格分隔符)。有些人可能认为它看起来更整齐,具有统一的列宽(=整个表中的最大位数),并且可以很容易地修改代码来执行此操作。

' 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