Random and negative numbers

前端 未结 7 706
鱼传尺愫
鱼传尺愫 2021-01-17 14:52

I have to generate numbers in range [-100; +2000] in c++. How can I do this with rand if there is only positive numbers available? Are there any fast ways?<

7条回答
  •  生来不讨喜
    2021-01-17 15:27

    Currently my C++ syntax is a little rusty, but you should write a function that takes two parameters: size and offset.

    So you generate numbers with the given size as maximum value and afterwards add the (negative) offset to it.

    The function would look like:

    int GetRandom(int size, int offset = 0);
    

    and would be called in your case with:

    int myValue = GetRandom(2100, -100);
    

提交回复
热议问题