以條件迴圈重複猜數字直至猜中為止
步驟如下:
1. 亂數產生一個1~100的數字
2. 使用者以InputBox輸入數字猜之
3. 利用If判斷此數字是否超過謎底,若超過則以msgbox物件上提示"小一點",否則提示"大一點"
4. 每猜一次,在InputBox提示語上顯示總次數,並要求繼續輸入直到輸入數字與謎底相同為止
5. 以MsgBox顯示猜中及總次數
Dim intAnswer As Integer, intGuess As Integer, intTotal As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Randomize()
intAnswer = Rnd() * 100 '不妨加到1000,增加難度!?
Do While intGuess <> intAnswer '除非猜中,否則一直要求輸入
intTotal = intTotal + 1
intGuess = InputBox("第" + Str(intTotal) + "次," + "請猜!!", "我猜我猜我猜猜猜", intGuess) '顯示次數及提示輸入
If intAnswer > intGuess Then MsgBox("大一點! 加油") '判斷輸入數字大小及提示
If intAnswer < intGuess Then MsgBox("小一點! 加油")
Loop
MsgBox("猜中了,共" + Str(intTotal) + "次") '猜中提示
End Sub
動動腦,改良此程式:
1.直接用InputBox提示
2.提示範圍及猜中機會等訊息 (加入適當的運算式)
3. InputBox及MsgBox的樣式 (參考先前InputBox及MsgBox實習內容)
4. 猜中後可續玩 (參考上週內容)
...............