How to do pick random math operations in a C program?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rhen18
    New Member
    • Dec 2009
    • 9

    How to do pick random math operations in a C program?

    Good day!
    Im working on a math drill program where the user is asked to answer random math problems that involves the +, -, /, *, and % operators.
    Now i dont know how to generate these randomly.
    What commands and codes could I use?
    So much thanks in advance!
    Have a fruitful new year!
  • Airslash
    New Member
    • Nov 2007
    • 221

    #2
    generate a randon int value from 0 to 4 and depending on the value you perform the correct action using a switch statement

    pseudo code:
    Code:
    // Generate a random int value in a range
    int val = GenerateRandomValue(0,4);
    
    // call the correct action
    switch(val)
    {
        case 0:
            // do the + stuff
        case 1:
            // do the - stuff
        case 2:
            // do the * stuff
        case 3:
            // do the / stuff
        case 4:
            // do the % stuff
    }

    Comment

    • puneetsardana88
      New Member
      • Aug 2009
      • 57

      #3
      You can use rand

      int k=rand()%5;

      Use Randomize to get different values for each compilation

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        using

        rand()%5

        is a poor idea because the algorithm often used in the C standard library often produces results with poor randomness in the low order bits of its result.

        Read C-Faq Question 13.16

        Comment

        Working...