2015-07-10 161 views
0

我目前正在做一个项目,并试图做出自己的数学测验。基本上,我有3个标签和一个文本框。在第一个和第三个标签中随机生成一个数字。在第二个标签中,选择一个数学运算符(+, - 或÷)。在文本框中,用户将输入一个等式的答案,这就给我带来了我想问的问题:VB - 数学测验检查答案

我可以做到一切都很好,但我无法绕过代码这将检查输入到文本框中的答案是否正确。

我已经试过......

If lbloperator.Text = "+" & txtsum.Text =num1 + num2 Then 
     msgbox("CORRECT") 
    End If 

,但它不工作。

最后,我想用计数器替换msgbox以计算在测验持续时间内获得的正确答案的数量。我也尝试过其他的东西,已经越来越错误:

Conversion from string "" to type 'Double' is not valid.

如果有帮助,一个按钮到位,以随机的操作并在标签数量和检查,如果答案是正确的。

谢谢

+0

你的代码的问题是你使用'&'这是一个连接运算符。它会将两个字符串拼接成一个,而不是检查它们。使用'AndAlso':'If lbloperator.Text =“+”AndAlso txtsum.Text = CStr(num1 + num2)' –

+0

非常感谢Visual Vincent,这似乎解决了它无法工作。 –

回答

2

也许这会有所帮助。

鉴于这些功能:

Dim dictionary = New Dictionary(Of String, Func(Of Double, Double, Double))() _ 
     From _ 
     { _ 
      {"+", Function(x, y) x + y}, _ 
      {"-", Function(x, y) x - y}, _ 
      {"*", Function(x, y) x * y}, _ 
      {"/", Function(x, y) x/y} _ 
     } 

    Dim process As Func(Of String, String, String, Double) = _ 
     Function(op, x, y) _ 
      dictionary(op)(Double.Parse(x), Double.Parse(y)) 

你现在可以做的事:

Dim operator = TextBox1.Text ' "+" 
    Dim num1 = TextBox2.Text ' "5" 
    Dim num2 = TextBox3.Text ' "4" 
    Dim result = process(operator, num1, num2) ' 9 

请让我知道如果这有助于我怎么可以扩大到把你带到任何你需要去。

+1

我喜欢这样 - 比我在下面的答案中拼凑出来的那种更清洁的解决方案。加上1。 –

+0

你能指导我到哪里我可以学习你使用的命令。我不明白发送的代码的顶部的一件事,为我的无知道歉,我绝对会将自己归类为初学者。 –

+0

你需要查找的两件事是'Dictionary '和匿名函数。 – Enigmativity

0

我建议你使用select语句,例如尝试这样的事情;假定四个文本框位于第一个数字的下方,第二个为运算符,第三个为第二个数字,最后为结果。转换为十进制允许用户输入类似2,5的内容,否则,事实上他们可能无法输入正确的操作符。

 Dim correctResults As Integer 


    Private Sub CheckResult() 
     Dim num1 As Decimal = CDec(textBox1.text) 
     Dim num2 As Decimal = CDec(TextBox3.Text) 
     Dim operator as String = TextBox2.Text 
     Dim result As Decimal = CDec(TextBox4.text) 

Select Case operator 

      Case "+" 

       If result = num1 + num2 Then 
        correctResults += 1 
       End If 
      Case "-" 
       If result = num1 - num2 Then 
        correctResults += 1 
       End If 


      Case "*" 

       If result = num1 * num2 Then 
        correctResults += 1 
       End If 

      Case "/" 

       If result = num1/num2 Then 
        correctResults += 1 
       End If 

      Case Else 

       Exit Sub 


     End Select 
    End Sub