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

    Random Math Operator

    Need to pick a random math operator without using array method. Need to use random line along with it.
  • #752127
    Hello,

    You can do with generating a random number like this


    Random rnd = new Random();
    int i = rnd.Next(0, 4);


    then use if... else to decide operators


    int a = 0;
    int b = 0;
    if (int==1)
    {
    int i = a + b;
    }
    if (int == 2)
    {
    int i = a - b;
    }
    if (int == 3)
    {
    int i = a / b;
    }
    if (int == 4)
    {
    int i = a * b;
    }

    Regards,
    Shakil Sama

  • #752128
    HI Christina,

    Sorry didn't get you. Can you please come in detail. Are you trying to generate the mathematical operator?
    If yes, you can use the if else condition like below-

    if(condition1)
    {
    //assign Addition;
    }
    else if(condition 2)
    {
    //assign multiplication;
    }
    and so on ...

    And if you are trying to generate the string, you can use the below-

    private string RandomString(int size, bool lowerCase)
    {
    StringBuilder builder = new StringBuilder();
    Random random = new Random();
    char ch ;
    for(int i=0; i<size; i++)
    {
    ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))) ;
    builder.Append(ch);
    }
    if(lowerCase)
    return builder.ToString().ToLower();
    return builder.ToString();
    }

    Hope this will help you !!

    Thanks,
    Ashutosh Jha
    http://tricksroad.com

  • #752133
    Hi,


    You should set opetation for all add,subtract,multiplication and division
    Than you can set if else condition and you will fulfil your need.

    Random rndNo = new Random();
    int operations = rndNo.Next(0, 4);
    if (operations==1)
    {
    //do stuff for addition

    }
    if (operations == 2)
    {
    //do stuff for subtraction

    }
    if (operations == 3)
    {
    //do stuff for multiplication

    }
    if (operations == 4)
    {
    //do stuff for division
    }

    I hope you got my point, 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

  • #752139
    Thank you so much for the clarification ! It makes so much sense plus I realize I can do a switch statement too. I appreciate your help!

  • #752456
    Hi Christina,

    Whenever you get solutions or nearer idea from anyone than always make habbit to select that perticular anwer as a best answer.
    So other members can trust on that without testing it and it is neccessary to motivate helpers too.
    I hope you got my point.

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


  • Sign In to post your comments