How do I get a specific range of numbers from rand

2019-01-04 01:56发布

srand(time(null));

printf("%d", rand());

Gives a high-range random number (0-32000ish), but I only need about 0-63 or 0-127, though I'm not sure how to go about it. Any help?

标签: c random
17条回答
Juvenile、少年°
2楼-- · 2019-01-04 02:14
double scale = 1.0 / ((double) RAND_MAX + 1.0);
int min, max;
...
rval = (int)(rand() * scale * (max - min + 1) + min);
查看更多
相关推荐>>
3楼-- · 2019-01-04 02:15

Just using rand() will give you same random numbers when running program multiple times. i.e. when you run your program first time it would produce random number x,y and z. If you run the program again then it will produce same x,y and z numbers as observed by me.

The solution I found to keep it unique every time is using srand()

Here is the additional code,

#include<stdlib.h>
#include<time.h>

time_t t;
srand((unsigned) time(&t));
int rand_number = rand() % (65 + 1 - 0) + 0 //i.e Random numbers in range 0-65.

To set range you can use formula : rand() % (max_number + 1 - minimum_number) + minimum_number

Hope it helps!

查看更多
走好不送
4楼-- · 2019-01-04 02:21

Or you can use this:

rand() / RAND_MAX * 65

But I'm not sure if it's the most random or fastest of all the answers here.

查看更多
太酷不给撩
5楼-- · 2019-01-04 02:22

check here

http://c-faq.com/lib/randrange.html

For any of these techniques, it's straightforward to shift the range, if necessary; numbers in the range [M, N] could be generated with something like

M + rand() / (RAND_MAX / (N - M + 1) + 1)
查看更多
迷人小祖宗
6楼-- · 2019-01-04 02:22

Updated to not use a #define

double RAND(double min, double max)
{
    return (double)rand()/(double)RAND_MAX * (max - min) + min;
}
查看更多
唯我独甜
7楼-- · 2019-01-04 02:25

This answer does not focus on the randomness but on the arithmetic order. To get a number within a range, usually we can do it like this:

// the range is between [aMin, aMax]
double f = (double)rand() / RAND_MAX;
double result = aMin + f * (aMax - aMin);

However, there is a possibility that (aMax - aMin) overflows. E.g. aMax = 1, aMin = -DBL_MAX. A safer way is to write like this:

// the range is between [aMin, aMax]
double f = (double)rand() / RAND_MAX;
double result = aMin - f * aMin + f * aMax;

Based on this concept, something like this may cause a problem.

rand() % (max_number + 1 - minimum_number) + minimum_number
// 1. max_number + 1 might overflow
// 2. max_number + 1 - min_number might overflow
查看更多
登录 后发表回答