vb.net - randomising operators visual basic -
i want program (visual basic) randomly select times (*) or divide (/) , used operator in equation later in program. haven't started declaration of variables. thanks.
you didn't provide code there can many solutions. have 2 operators, think best way go use conditions. basics use random class, , if or case.
the code can this:
function dosomeoperation(byval double, byval b double, optional byref op string = "") double dim rnd new random() select case rnd.next(0, 2) case 1 op = "/" return / b case else op = "*" return * b end select end function this code return operation result, , optionally operation used in op parameter. rnd.next(0, 2) statement returns either 0 or 1 (because maxvalue 2, exclusive upper bound).
*in real life should check result doesn't exceed double limits, , try..catch.
example of function use in console app:
dim double = 8 dim b double = 2 dim op string = "" dim result double = dosomeoperation(a, b, op) console.writeline(string.format("{0} {1} {2} = {3}", a, op, b, result)) console.readkey() 'output: 8 * 2 = 16 or 8 / 2 = 4 addition
to answer @wickedjdg comment, if want a , b randomly selected between 1 , 12, can use function:
function dosomerandomoperation(optional byref double = 0, optional byref b double = 0, optional byref op string = "") double dim rnd new random() = rnd.next(1, 13) b = rnd.next(1, 13) select case rnd.next(0, 2) case 1 op = "/" return / b case else op = "*" return * b end select end function
Comments
Post a Comment