電腦 Visual Basic 2010 Express

2013-10-03 7:17 am
Write a program that prints the following pattern. The number of rows (maximum 9)
should be selected by the user.
Example:
Enter the number of rows:6
1
121
12321
1234321
123454321
12345654321

Enter the number of rows:4
1
121
12321
1234321
中間的數字是置中的,如果唔明個pattern,可 copy 下列 code 到 VB 試下

我已盡力打了下列 code
Console.Write("Enter the number of rows: ")
Dim numRows As Integer = Val(Console.ReadLine())
If numRows > 0 And numRows < 10 Then
Dim h, j, num, numSpaces As Integer
For h = 1 To numRows
num = h * 2 - 1
numSpaces = numRows - h
For j = 1 To numSpaces
Console.Write(" ")
Next
For j = 1 To num
Console.Write(j)
Next
Console.WriteLine()
Next
Console.ReadLine()
Else
Console.WriteLine("Error! The range is between 1 and 9.")
Console.ReadLine()
End If
但卻顯示出
1
123
12345
1234567
123456789
希望電腦 Visual Basic 高手能夠幫助我
最好打埋你所寫的code 以及我的 code 要改的地方

回答 (1)

2013-10-06 12:01 pm
✔ 最佳答案
雖然我不會visual basic.
你應該先分析一下那個pattern
首先長度是
1+0
2+1
3+2
4+3
即是n+(n-1)
一直加到n而當大過n是就減
所以程式應該這樣
Console.Write("Enter the number of rows: ")
Dim numRows As Integer = Val(Console.ReadLine())
If numRows > 0 And numRows < 10 Then
Dim n, i, j, totalLen As Integer
For n = 1 To numRows
totalLen = n + (n-1)
j = 1
For i = 1 To totalLen
If i > n Then
Console.Write(j++)
Else
Console.Write(j--)
End If
Next
Console.WriteLine()
Next
Console.ReadLine()
Else
Console.WriteLine("Error! The range is between 1 and 9.")
Console.ReadLine()
End If

2013-10-06 04:03:48 補充:
上面個If倒轉左= =
應該大過時--才對
If i > n Then
Console.Write(j--)
Else
Console.Write(j++)
End If


收錄日期: 2021-04-13 19:44:28
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20131002000051KK00252

檢視 Wayback Machine 備份