2011-08-06 56 views
3

我在乘法表程序中需要幫助。該程序通過文本框向用戶詢問二維數組的維數。當檢索到維度時,程序應該在表單中整齊地打印給定尺寸的乘法表。問題是,我不知道如何整潔地以表格格式打印數組。它是這樣的一個樣本輸出:格式化和打印一個二維數組(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 

什麼代碼可以使這個程序在表格中整齊地打印表格?

回答

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 
+0

非常感謝!^_ ^現在我有一個想法如何解決問題。 :) –