VBA 进行随机计算并确认正确答案

VBA doing random calculations and confirming right answer

下面的代码给你一个随机计算,你提供一个答案,程序检查你的答案是否正确。总之你得到 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 = 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