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