Excel and Visual Basic语言问题
PublicSubGetANumber()DimrndnumberAsInteger,countAsInteger,numberAsIntegerDimlowAsInte...
Public Sub GetANumber()
Dim rndnumber As Integer, count As Integer, number As Integer
Dim low As Integer, high As Integer
Dim current As Integer, best As Integer
Dim input_str As String
best = Range("B4").Value
low = 1
high = 100
number = 0
Do While (number < 1 Or number > 100)
input_str = InputBox("Give a whole number between 1 and 100")
Do While Not IsNumeric(input_str)
input_str = InputBox("You should type a number!!!!")
Loop
number = Val(input_str)
If (number < 1 Or number > 100) Then
MsgBox ("Between 1 and 100, please... !! ")
End If
Loop
Randomize
count = 0
Do While (number <> rndnumber)
rndnumber = Int((high - low + 1) * Rnd + low)
count = count + 1
' Cells(count, 1).Value = rndnumber
Loop
MsgBox ("The random number generator needed " & count & " cycles to get the same number you gave as a target value ")
current = count
Range("B2").Value = current
If (current < best) Then
Range("B4").Value = current
End If
ActiveWorkbook.Save
End Sub 展开
Dim rndnumber As Integer, count As Integer, number As Integer
Dim low As Integer, high As Integer
Dim current As Integer, best As Integer
Dim input_str As String
best = Range("B4").Value
low = 1
high = 100
number = 0
Do While (number < 1 Or number > 100)
input_str = InputBox("Give a whole number between 1 and 100")
Do While Not IsNumeric(input_str)
input_str = InputBox("You should type a number!!!!")
Loop
number = Val(input_str)
If (number < 1 Or number > 100) Then
MsgBox ("Between 1 and 100, please... !! ")
End If
Loop
Randomize
count = 0
Do While (number <> rndnumber)
rndnumber = Int((high - low + 1) * Rnd + low)
count = count + 1
' Cells(count, 1).Value = rndnumber
Loop
MsgBox ("The random number generator needed " & count & " cycles to get the same number you gave as a target value ")
current = count
Range("B2").Value = current
If (current < best) Then
Range("B4").Value = current
End If
ActiveWorkbook.Save
End Sub 展开
若以下回答无法解决问题,邀请你更新回答
展开全部
这个程序是让你输入一个数,然后电脑会随机产生一个0~1之间的随机数,以此作为比例在1(low)到100(high)之间插值并对结果四舍五入取整。如果不等就计数1次并重新循环,直到
与你输入的值相等为止。程序会输出该次循环的次数并与最好记录相对比,要是该次循环的次数比前次小则把该次的循环次数设置为最好记录。
该程序有个bug,即B4中的值必须要输入一个大于0的数,假设一开始输入的是一个比较小的数或者不输入那么记录的最好次数并不是真实的情况。
建议把末尾的一句
If ( current < best) Then 改成
If (Len(Trim(Cells(4, 2))) = 0 Or current < best) Then
这样一开始不必在B4中输入任何值,程序会自动在B4中输出最好结果。
Ps.作业还是自己做的好,万一你老师会用baidu你就惨了,作弊的后果很严重的说
与你输入的值相等为止。程序会输出该次循环的次数并与最好记录相对比,要是该次循环的次数比前次小则把该次的循环次数设置为最好记录。
该程序有个bug,即B4中的值必须要输入一个大于0的数,假设一开始输入的是一个比较小的数或者不输入那么记录的最好次数并不是真实的情况。
建议把末尾的一句
If ( current < best) Then 改成
If (Len(Trim(Cells(4, 2))) = 0 Or current < best) Then
这样一开始不必在B4中输入任何值,程序会自动在B4中输出最好结果。
Ps.作业还是自己做的好,万一你老师会用baidu你就惨了,作弊的后果很严重的说
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询