WickedJDG - 2 years ago 132
Vb.net Question

# randomising operators visual basic

I want my program (visual basic) to randomly select times (*) or divide (/) and for that to be used as an operator in an equation later in the program. I haven't started as this is for the declaration of variables. Thanks.

You didn't provide any code so there can be many solutions. You only have two operators, so I think the best way to go would be to just use conditions. The basics are to use the `Random` class, and an `If` or a `Case`.

The code can look like this:

``````Function DoSomeOperation(ByVal a As Double, ByVal b As Double, Optional ByRef op As String = "") As Double
Dim rnd As New Random()
Select Case rnd.Next(0, 2)
Case 1
op = "/"
Return a / b
Case Else
op = "*"
Return a * b
End Select
End Function
``````

This code will return the operation result, and optionally the operation used in the `op` parameter. The `rnd.Next(0, 2)` statement returns either `0` or `1` (because the maxValue `2`, is an exclusive upper bound).

*In real life you should probably check the result doesn't exceed the `Double` limits, and do a `try..catch`.

Example of the function use in a Console app:

``````    Dim a As Double = 8
Dim b As Double = 2
Dim op As String = ""
Dim result As Double = DoSomeOperation(a, b, op)
Console.WriteLine(String.Format("{0} {1} {2} = {3}", a, op, b, result))
'Output: 8 * 2 = 16 or 8 / 2 = 4
``````

To answer @WickedJDG comment, if you want `a` and `b` randomly selected between 1 and 12, you can use this function:

``````Function DoSomeRandomOperation(Optional ByRef a As Double = 0, Optional ByRef b As Double = 0, Optional ByRef op As String = "") As Double
Dim rnd As New Random()
a = rnd.Next(1, 13)
b = rnd.Next(1, 13)
Select Case rnd.Next(0, 2)
Case 1
op = "/"
Return a / b
Case Else
op = "*"
Return a * b
End Select
End Function
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download