float rand

how to rand a number between [0,1).
http://www.cplusplus.com/reference/cstdlib/rand/

https://www.youtube.com/watch?v=naXUIEAIt4U&ab_channel=thenewboston

https://www.youtube.com/watch?v=sxmxU3zTVH8&ab_channel=SchoolFreeware

Edit: Your question is extremely confusing. What does rand have anything to do with float? Do you mean Round and not rand?
Last edited on
I think he wants random floating point values between 0 and 1 ( 1.0 / rand() )
Oh ye, that does make a little bit of sense, wish they actually asked properly though.
I did mean something like that:
I think he wants random floating point values between 0 and 1 ( 1.0 / rand() )

but not realy
i'm a begginer don't give me random libary and such.

just a simple rand command for num [0,1)
sigh...
Last edited on
i'm a begginer don't give me random libary and such.


You're going to have to learn how to read documentation if you hope to get anywhere as a programmer.

just a simple rand command for num [0,1)



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <random>
#include <ctime>

#include <iostream>

float floatrand()
{
    static std::mt19937 rng_engine( (unsigned)time(nullptr) );
    static std::uniform_real_distribution<float> distribution;


    return distribution(rng_engine);
}


int main()
{
    std::cout << "10 random numbers between [0,1):\n";

    for(int i = 0; i < 10; ++i)
        std::cout << floatrand() << '\n';
}
don't give me random libary and such

The cstdlib is no less a "library" than what the random is. They are both part of the same standard library, but the use of rand() is deprecated.

Deprecated features can be omitted from the next version of the standard library. In other words, when that happens, all the programs that have been using rand() and have to be compiled either cannot use the future library or have to be changed the other style.

Do you want to learn two different styles? Would it not be easier for you to simply learn the use of std::uniform_real_distribution?


just a simple rand command

That would be a disservice to you. The very first link of TarikNeaj's first post describes the rand(). It tells what range of values the rand() does return. What is left to do, is to scale that range into your desired range.

For example, say that you get range [0,3). Four different values. 0, 1, 2, 3.
0.0/4, 1.0/4, 2.0/4, 3.0/4, i.e. 0.0, 0.25, 0.5, 0.75 are in range [0,1).

The only tricky thing is that integer division does not work for this task. You have to force floating point division. That requires static_cast. See http://en.wikipedia.org/wiki/Static_cast
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main(){
	
	srand(time(0));	
	
	for(int i=0; i<10; i++){
		int a = rand()%100;
		float r_float; // 0.00 to 0.99
		r_float = a/100.0;
		printf("%f \n", r_float);
	}	
	
}
Topic archived. No new replies allowed.