-2

Possible Duplicate:
In C, how do I get a specific range of numbers from rand()?
Generate a random number within range?

I'm stuck on how to use the rand() function and include a range for that random number. I need a random number between 67.00 and 99.99 only to be printed.

This is what I have tried, but failed with...

#include <stdio.h>
#include <stdlib.h>

int main(void)

{
    int x = rand();

    if(x>=67.00)
    if(x<=99.99)
          printf("%d\n",x);
        else
        printf("not in range");
}   
Community
  • 1
  • 1
R123
  • 1
  • 1
  • 1

1 Answers1

3

Instead of checking if the result is in the range, you can force the result to be in the range that you want:

int HIGH = 100;
int LOW = 67;
int rnd = LOW + (rand() % (HIGH-LOW));

The value of rnd is in the range between LOW and HIGH-1, inclusive.

If you do not want to force the number into range, change your condition to

if(x>=67.00 && x<=99.99)

Currently, the else belongs to the inner if, so the second printf does not happen when the number is less than 67.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • But his requirement is for floats. Your solution will return only integers. You should use 6700 and 10000 instead. – Shredderroy Jan 28 '13 at 00:35
  • I dont want the number to be forced, so is there an alternative way? – R123 Jan 28 '13 at 01:06
  • @RamonCastillo Sure, you can - take a look at the latest edit. – Sergey Kalinichenko Jan 28 '13 at 01:37
  • ok here's the my edited code... also I get the same out being "not in range" which is expected every time I run the program because it is not seeded correct? – R123 Jan 28 '13 at 01:55
  • #include #include int main(void) { int x = rand(); if(x>=67.00 && x<=99.99) printf("%d\n",x); else printf("not in range"); – R123 Jan 28 '13 at 01:56