Generating random number between [-1, 1] in C?

后端 未结 7 869
北恋
北恋 2020-12-08 21:57

I have seen many questions on SO about this particular subject but none of them has any answer for me, so I thought of asking this question.

I wanted to generate a r

7条回答
  •  青春惊慌失措
    2020-12-08 23:00

    For starters, you'll need the C library function rand(). This is in the stdlib.h header file, so you should put:

    #include 
    

    near the beginning of your code. rand() will generate a random integer between zero and RAND_MAX so dividing it by RAND_MAX / 2 will give you a number between zero and 2 inclusive. Subtract one, and you're onto your target range of -1 to 1.

    However, if you simply do int n = rand() / (RAND_MAX / 2) you will find you don't get the answer which you expect. This is because both rand() and RAND_MAX / 2 are integers, so integer arithmetic is used. To stop this from happening, some people use a float cast, but I would recommend avoiding casts by multiplying by 1.0.

    You should also seed your random number generator using the srand() function. In order to get a different result each time, people often seed the generator based on the clock time, by doing srand(time(0)).

    So, overall we have:

    #include 
    srand(time(0);
    double r = 1.0 * rand() / (RAND_MAX / 2) - 1;
    

提交回复
热议问题