Thread: Generating random number from set

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    15

    Generating random number from set

    The problem asks me to write a c statement that will assign an int variable a random number from [25, 50, 75, 100]

    I am thinking of using rand() but I'm not sure how

    perhaps?
    for (int i = 0; i <=100;i*2)
    int random_number=rand(i);

    I'm not even sure that's allowed
    Last edited by Hybodus; 12-20-2010 at 10:51 AM.

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    I would put your set in an array:
    Code:
     int set[] = { 25, 50, 75, 100 };
    Then you can use your rand() result as an index into set:
    Code:
     int random_number = set[<random number between 0 and 3 inclusive>];
    If you understand what you're doing, you're not learning anything.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    itsme86's suggestion is a more general solution, but in this case you can map the integers in the range [0, 3] to those numbers by a simple formula, e.g., ((rand() % 4 + 1) * 25).
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Logical errors with seach function
    By Taka in forum C Programming
    Replies: 4
    Last Post: 09-18-2006, 05:20 AM
  2. Counting number from a random file
    By kamisama in forum C Programming
    Replies: 42
    Last Post: 02-22-2005, 05:16 PM
  3. non repeating random number generation?
    By gencor45 in forum C# Programming
    Replies: 1
    Last Post: 02-08-2005, 05:23 PM
  4. Random Number Generating
    By K.n.i.g.h.t in forum C Programming
    Replies: 9
    Last Post: 01-30-2005, 02:16 PM
  5. How do I restart a random number sequence.
    By jeffski in forum C Programming
    Replies: 6
    Last Post: 05-29-2003, 02:40 PM