4 Replies - 38779 Views - Last Post: 10 October 2005 - 10:19 PM Rate Topic: -----

#1 ExitToShell();  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 26
  • Joined: 09-October 05

Use of rand() function

Posted 10 October 2005 - 09:28 AM

This is my first post in the C++ section, so I'll just say it now that I'm teaching myself with two textbooks(one for the lessons, the other for "labs" of a sort to make sure you know your stuff), but I'm not being graded ;)

Alright, as I learn I've been adding on little tidbits of code here and there to a little rpg I doubt will ever finish :P

The question I have involves that:


For the random function ( rand() ), how could I get it to give me a random number 2-4, if rand() only gives a random number between 0 and whatever number you give it?

Is This A Good Question/Topic? 0
  • +

Replies To: Use of rand() function

#2 dorknexus  Icon User is offline

  • or something bad...real bad.
  • member icon

Reputation: 1256
  • View blog
  • Posts: 4,618
  • Joined: 02-May 04

Re: Use of rand() function

Posted 10 October 2005 - 09:31 AM

just get a random number between 0 and 2 and add 2 to it. the best rule to remember is to set up the function like this



int num = rand() % (HIGH - LOW) + LOW;



in this case high = 4 and low = 2

int num = rand() % (4 -2) + 2;

//or

int num = rand() % (2) + 2;


Was This Post Helpful? 1

#3 ExitToShell();  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 26
  • Joined: 09-October 05

Re: Use of rand() function

Posted 10 October 2005 - 09:44 AM

Wow, that was a quick reply, you guys are fast ;)

Thank you, this has helped me finish implementing an equation :)
Was This Post Helpful? 0
  • +
  • -

#4 dorknexus  Icon User is offline

  • or something bad...real bad.
  • member icon

Reputation: 1256
  • View blog
  • Posts: 4,618
  • Joined: 02-May 04

Re: Use of rand() function

Posted 10 October 2005 - 09:45 AM

Not a problem, hope DIC can be just as helpful for you in the future.
Was This Post Helpful? 0
  • +
  • -

#5 born2c0de  Icon User is offline

  • printf("I'm a %XR",195936478);
  • member icon

Reputation: 180
  • View blog
  • Posts: 4,667
  • Joined: 26-November 04

Re: Use of rand() function

Posted 10 October 2005 - 10:19 PM

You can use the random() function as well for simple ranges.
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

/* prints a random number in the range 0 to 99 */
int main(void)
 {
    randomize();
    printf("Random number in the 0-99 range: %d\n", random (100));
    return 0;
}


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1