-6

How can I get a floating point number to be random between two digits and for that to be 4 decimal places. Example

Between the two digits between 0-1 and a random 4 decimal place number between them would be 0.0008f.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Fdoh
  • 1
  • 3
  • 1
    Have you tried anything yourself? There is a lot of information on this already out there. – NathanOliver May 09 '16 at 17:22
  • Hi, I have used float r = ((double)rand() / (RAND_MAX)) + 4 + (rand() % 1); But I can't get it to work @NathanOliver – Fdoh May 09 '16 at 17:23
  • @Fdoh `rand() % 1` Modulo(1) is useless, isn't it? Remainder of something divided by 1 will always be zero. And BTW ` + 4` doesn't push you up to 4 decimal digits. – πάντα ῥεῖ May 09 '16 at 17:25
  • 2
    You can use a [`std::uniform_real_distribution`](https://stackoverflow.com/questions/37121776/c-random-float-number-that-is-4-decimal-places) – Cory Kramer May 09 '16 at 17:26
  • Generate a random number `[0000, 9999]` then divide by `1,0000` – Martin York May 09 '16 at 17:27
  • Can you create a random integer that is between two integers? Are you ok with limiting your solution to handle values less than 10^15 or so? – Yakk - Adam Nevraumont May 09 '16 at 17:27
  • 2
    Possible duplicate of [C++ random float number generation](http://stackoverflow.com/questions/686353/c-random-float-number-generation) – FiReTiTi May 09 '16 at 19:26

2 Answers2

2

As @NathanOliver explained, there is a lot of info out there. I recommend to do some research.

An easy solution would be to get a random between [1-10[K and then divide the value by 10K.

You can use integers all the time if you do not need the division. Depends what you want to do with your code.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
d4nk
  • 21
  • 3
0

Generate a random number between 1 and 9999 (both inclusive). Then divide that number by 10000 and you have the result you want.

And please use the facilities in <random> rather than srand()/rand(). The latter produces horrible quality random numbers.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70