Random number between two floating point numbers

Hello I want to generate a random number between 0.2 and -0.2

here is what i have so far

float randomNumber;
randomNumber = (float)random()%((-0.2f+0.2f)+1.0f)+0.2f

can anyone see where i went wrong or if somebody knws the answer could you pls help me


edit even between -1 and 1 would be of great help

Thanking You
Last edited on
Hmm you could just do:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main()
{
    srand(time(0));
    double i = 0, d = 0;
    i = rand() % 40 - 20; //Gives a number between -20 and +20;
    d = i / 100; //Reduces this number to the range you want.
    cout << d;
    return 0;
}


Multiplying 40 and 20 and 100 by ten will give you an extra digit after the decimal point. For example, 4000, 2000 and 10000 (multiplying each by ten twice) will give you 0.xxxx

Edit: Forgot to seed.



Last edited on
I don't know if there exist random() in c++, where did you find that?

I know you can use rand() to produce pseudo-random integer numbers.

1
2
3
4
5
6
7
#include <ctime>
#include <cstdlib>

srand ( time(NULL) ); //just seed the generator
int r = rand()%4000 - 2000; //this produces numbers between -2000 - +2000

double random_num = r/10000.0; //this will create random floating point numbers between -0.2 upto //0.2 


Of course this has some precision of 4 digits. If you want more just increase the range of number generated.
Last edited on
Topic archived. No new replies allowed.