有誰知道我會隨機產生一個基本的數學問題,其答案總是1,2,3或4. 因此,例如使用兩個隨機數8和4我可能會顯示的問題:vb.net隨機數學
8/4,從而在此情況下,答案是2。其它實施例:2 * 2,8/8,4 + 0等等,但 答案總是在範圍爲1〜4。 由於
有誰知道我會隨機產生一個基本的數學問題,其答案總是1,2,3或4. 因此,例如使用兩個隨機數8和4我可能會顯示的問題:vb.net隨機數學
8/4,從而在此情況下,答案是2。其它實施例:2 * 2,8/8,4 + 0等等,但 答案總是在範圍爲1〜4。 由於
我是po點擊下面的想法。
如果您只想使用正整數(在此示例中,counterPartNumerator
可能不是),則需要進行一些調整。
玩得開心!
Private _possibleNumerators() As Integer = {2, 4, 8, 12, 15, 20, 25, 32, 40} ' Random numbers I arbitrarily chose
Private _possibleResults() As Integer = {1, 2, 4, 8}
Friend Enum Operation As Integer
Add = 0
Subtract = 1
Multiply = 2
Divide = 3
End Enum
Private _randomGen As New Random
Public Sub ShowArithmeticExpression()
Dim randomNumerator As Integer = GetRandom(_possibleNumerators)
Dim counterPartNumerator As Decimal
Dim randomDesiredResult As Integer = GetRandom(_possibleResults)
Dim randomOperation As Operation = GetRandom([Enum].GetValues(GetType(Operation)))
Dim operationSymbol As String
' Find counterPartNumerator
Select Case randomOperation
Case Operation.Add
counterPartNumerator = randomDesiredResult - randomNumerator
operationSymbol = "+"
Case Operation.Subtract
counterPartNumerator = randomNumerator - randomDesiredResult
operationSymbol = "-"
Case Operation.Multiply
counterPartNumerator = randomDesiredResult/randomNumerator
operationSymbol = "*"
Case Operation.Divide
counterPartNumerator = randomNumerator * randomDesiredResult
operationSymbol = "/"
End Select
Console.WriteLine(String.Format("{0} {1} {2} = ?", randomNumerator, operationSymbol, counterPartNumerator))
Console.WriteLine(String.Format("Result = {0}", randomDesiredResult))
End Sub
Private Function GetRandom(numberSet As Integer()) As Integer
Dim minValue, maxValue As Integer
' Could simplify this using Linq. Eg: minValue = numberSet.Min() : maxValue = numberSet.Max()
For Each number In numberSet
If number < minValue Then minValue = number
If number > maxValue Then maxValue = number
Next
While True
Dim valueReturn As Integer = _randomGen.Next(minValue, maxValue)
If numberSet.Contains(valueReturn) Then
Return valueReturn
End If
End While
Return -1
End Function
非常感謝J. - 不得不做幾個變化,但在箱子外面工作 - 乾杯:-) – ITECH 2013-04-04 12:02:08
試試以下代碼
Dim xGenerator As System.Random = New System.Random()
Dim xTemp As Integer = 0
Dim c As Integer = 0
Dim xRndNo As New List(Of Integer)
While Not xRndNo.Count = 2
xTemp = xGenerator.Next(0, 9)
If c = 0 Then
xRndNo.Add(xTemp)
Else
If (xRndNo.Item(0) + xTemp) Or (xRndNo.Item(0) - xTemp) Or (xRndNo.Item(0) * xTemp) Or (xRndNo.Item(0)/xTemp) <= 4 And ((xRndNo.Item(0) + xTemp) Or (xRndNo.Item(0) - xTemp) Or (xRndNo.Item(0) * xTemp) Or (xRndNo.Item(0)/xTemp)) > 0 Then
xRndNo.Add(xTemp)
End If
End If
c = +1
End While
需要一些清晰的輸入和預期的輸出。 – 2013-04-04 11:24:01