有谁知道我将如何随机生成一个基本的数学问题,其中答案总是 1、2、3 或 4。因此,例如使用两个随机数 8 和 4,我可能会显示问题:
8 / 4 所以在这种情况下答案是 2。其他示例:2*2、8/8、4+0 等,但答案始终在 1 到 4 的范围内。谢谢
我在下面发布一个想法。
如果您只想使用正整数(在此示例中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
尝试以下代码
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