2015-01-14 47 views
0

這是到目前爲止我的代碼如何隨機在Visual Basic(控制檯)一個數學函數/操作員

Module Module1 

Sub Main() 

    Randomize() 

    Dim number1 As Integer 
    Dim number2 As Integer 
    Dim answer As Integer 
    Dim userAnswer As Integer 
    Dim name As String 


    Console.WriteLine("Hello! Welcome to your Maths Quiz! Please enter your name >") 
    name = Console.ReadLine 
    Console.WriteLine("Nice to meet you " + name + ". Lets start the quiz") 

    Randomize() 
    number1 = Rnd() * 11 + 1 
    number2 = Rnd() * 11 + 1 
    answer = number1 + number2 


    Try 
     For i As Integer = 0 To 10 
      Console.WriteLine("What is " & number1 & " + " & number2 & " = ?") 
      userAnswer = Console.ReadLine 
      If userAnswer = answer Then 
       Console.WriteLine("Correct!") 
      Else 
       Console.WriteLine("Incorrect, the answer was " & answer) 
      End If 
     Next 
    Catch ex As InvalidCastException 
     Console.WriteLine("Oops you have typed in a number, please start over") 
    End Try 

    Console.ReadKey() 

End Sub 
End Module 

我需要創建一個隨機函數來發生的「+」號的,我已經試過方法很多,但輸出出現奇怪的,我想知道如果你能幫助,謝謝

+0

讓我們看看一些你已經嘗試過,然後我們可以幫助您解決或改進。 – aphoria

回答

1

如果你打算爲+ - * /然後我會做到這一點,如果只+ - ,並且可以與IIF去statments

創建一個新的隨機變量運算符

op = Int(Rnd() * 4) '0+ 1- 2* 3/ 

計算anwser與函數

answer= calc(number1, number2, op) 

Function calc(n1, n2, op) 
    If op = 0 Then calc = n1 + n2 
    If op = 1 Then calc = n1 - n2 
    If op = 2 Then calc = n1 * n2 
    If op = 3 Then calc = n1/n2 
End Function 

還有1個功能得到運營商的標誌

Console.WriteLine("What is " & number1 & s_op(op) & number2 & " = ?") 

Function s_op(op) 
    If op = 0 Then s_op = "+" 
    If op = 1 Then s_op = "-" 
    If op = 2 Then s_op = "*" 
    If op = 3 Then s_op = "/" 
End Function