You must Sign In to post a response.
  • Category: Visual Studio

    Randomly choose math operator

    I have to randomly decide which math operator to use ( +, -, *, /) and store the symbol.
    I was thinking of using a string or char to store the symbols however I'm not sure on how to type this out in order to randomly choose one out of four math operators.
    I've used this below to have my application choose a random number 1 through 10.

    int answer = 0;
    Random number = new Random();
    answer = number.Next(1,10);
  • #752070
    Hi Christina,

    I think you have solved your problem.
    What is an issue , is it any kind of issue with it?
    If you wondering how to do that than you can do it like that.

    string strMath = "+,-,*,/";
    for (int i = 0; i < strMath.Split(',').Length; i++)
    {
    int answer = 0;
    Random number = new Random();
    answer = number.Next(0, strMath.Split(',').Length);

    string Mathoperator = strMath.Split(',')[answer].ToString();
    }

    I hope this will solve your issue, if still you have an issue than i'll get back to you.

    Regards,
    Nirav Prabtani (Senior Web Developer)
    Email : niravjprabtani@gmail.com
    blog : niravprabtani.blogspot.in

  • #752124
    Thank you that works!

  • #752126
    I was actual able to do it a different way once I manipulated the code some so it's
    string[] manyStrings = {"+", "-", "*", "/"};
    Random Rstring = new Random();
    string symbol = manyStrings[Rstring.Next(0, manyStrings.Length)];
    however now I'm stuck on my if statement to show points earned and point total. Here's what I have
    do
    {

    Console.Clear();
    numberOne = number.Next(1, 10);
    numberTwo = number.Next(1, 10);
    symbol = manyStrings[Rstring.Next(0, manyStrings.Length)];

    //Calculation of the answer prior to the user inputting their solution
    if (symbol == "*")
    {
    answer = numberOne * numberTwo;
    }
    else if (symbol == "+")
    {
    answer = numberOne + numberTwo;
    }
    else if (symbol == "-")
    {
    answer = numberOne - numberTwo;
    }
    if (symbol == "/")
    {
    answer = numberOne / numberTwo;
    }
    for (int i = 1; i >= 1; i++)
    {
    Console.WriteLine("\t" + "### Math Problems ###");
    Console.Write("Problem {0}: {1} {2} {3} = ", i, numberOne, symbol, numberTwo);
    userA = (Convert.ToInt32(Console.ReadLine()));
    pointsTotal += 5;
    averageM = pointsTotal / (i*5);

    if (userA == answer)
    ----->>>> This is what I'm stuck on below {

    Console.WriteLine("Points Earned: 5" + "\t Point Total: " + "{0}" + "\t Average: " + "{1:P)", pointsTotal, averageM);
    }

    }
    } while (runApp == true);

  • #752159
    try is.




    char[] chrSymbol = {'^','*','/','-','+'}
    int answer = 0;
    Random number = new Random();
    answer = number.Next(0,3);

    char chr = chrSymbol[answer];

    Thanks & Regards
    Anil Kumar Pandey
    Microsoft MVP, DNS MVM


  • Sign In to post your comments