【问题标题】:VBA doing random calculations and confirming right answerVBA 进行随机计算并确认正确答案
【发布时间】:2018-10-26 13:58:49
【问题描述】:

下面的代码给你一个随机计算,你提供一个答案并程序检查你的答案是否正确。总之,你得到 5 个例子来解决。最后,我想创建一个简单的 MsgBox 说明用户在多少情况下是正确的 - 正确答案的数量。

此 MsgBox 当前由“g”表示。不幸的是 g = b + 0 与 g = b - 1 结合起来不是正确的方法。

有人可以帮忙吗?谢谢!

Sub Main2()

Dim b, e, f, s1, s2 As Byte
Dim g As String

    g = 0
    For b = 1 To 5

    e = Round(Rnd() * 10)
    f = Round(Rnd() * 10)
        MsgBox ("Count: ") & Str(e) & (" *") & Str(f)
    s1 = InputBox("What's the result?")

    s2 = e * f
    If s1 = s2 Then
        MsgBox ("Correct")
        g = b + 0

    Else
        MsgBox ("Incorrect! Right answer is") & Str(s2)
        g = b - 1

        End If

    Next b

    MsgBox ("Amount of correct answers: ") & Str(g)

End Sub

【问题讨论】:

  • 肯定是g=g+1 是正确答案,g=g-1 是错误答案,还是我遗漏了什么?您可能还希望 RANDOMIZE TIMER 随机化每次运行。

标签: vba calculation msgbox


【解决方案1】:

用途:

g = g + 1

为了正确并从错误中删除g = b - 1,因为您根本不想增加g。

您还需要将g 调暗为数字而不是字符串

Dim g as Long

还有

Dim b, e, f, s1, s2 As Byte

只会将s2 声明为Byte,其他将声明为Variant

用途:

Dim b As Byte, e As Byte, f As Byte, s1 As Byte, s2 As Byte

Sub Main2()

    Dim b As Byte, e As Byte, f As Byte, s1 As Byte, s2 As Byte
    Dim g As Long

    g = 0
    For b = 1 To 5

        e = Round(Rnd() * 10)
        f = Round(Rnd() * 10)
        MsgBox ("Count: ") & cStr(e) & (" * ") & cStr(f)
        s1 = InputBox("What's the result?")

        s2 = e * f

        If s1 = s2 Then
            MsgBox ("Correct")
            g = g + 1    
        Else
            MsgBox ("Incorrect! Right answer is") & cStr(s2)
        End If

    Next b

    MsgBox ("Amount of correct answers: ") & cStr(g)

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 2017-08-27
    相关资源
    最近更新 更多