randomizer

This is a discussion on randomizer within the C++ Programming forums, part of the General Programming Boards category; hi, i want to create a program that will randomly give me a number between 0 and 11 everytime i ...

  1. #1
    Registered User
    Join Date
    Sep 2004
    Posts
    84

    randomizer

    hi,

    i want to create a program that will randomly give me a number between 0 and 11 everytime i call the function.

    is there a math function that will automatically do this for me?

    barneygumble742

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    The function you're looking for is rand, from cstdlib:
    Code:
    #include <cstdlib>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
      for ( int i = 0; i < 10; i++ ) {
        int r = 1 + rand() % 10;
        cout<< r <<'\n';
      }
    }
    rand returns a value in the range [0,RAND_MAX), so you'll need to force the range down into what you want. When you say between 0 and 11, I'm assuming that the valid numbers are 1,2,3,4,5,6,7,8,9, and 10, which is why I force the range into [0,10) with the remainder operator and then add 1.

    You probably also want to look up the srand function if you find that you need a different sequence with every run of the program.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Randomizer for CounterStrike - help
    By cj348879 in forum C++ Programming
    Replies: 4
    Last Post: 03-18-2002, 03:37 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21