Can you create a random decimal number between two other numbers?

I'm working on a program and I was trying to figure out how to create a random fraction number between two other numbers.

Something like:

1
2
3
4
5
6
num3 = rand()[12,16];

num3 = 14.5;
//or
num3 = 12.8;
//etc 


Is it possible?
Yes.
1
2
3
double u;
srand( unsigned(time(NULL) );
u=(double)rand()/(RAND_MAX+1)*(16-12)+12

u is random value between 12 and 16.
Last edited on
Excellent! but one problem with it is that since rand creates for a number with several several decimal spaces, I guess the system isn't given much time to increase the number by a good margin.

So when I test it out the number increases by something like 0.00002xxxxx every couple of seconds. But what I need it for, it needs to be a lot faster.

Is there a way to have it so rand() only creates a number with 3-4 decimal spaces?
Last edited on
Try out this.it is much more randomised:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;

int main()
{
double u;
srand( unsigned(time(NULL)));
for(int i = 0;i< 10 ; i++)
{
u=(double)rand()/(RAND_MAX + 1)+12+(rand()%4);
cout<<"\t"<<u;
}
return 0;
}



Its output when i ran it:
14.5395 15.2107 12.9962 14.8939 12.8037 15.0763 13.4891 14.4526 13.0824 14.3426
if you only want 4 decimal places:

 
double u = (rand() % (160000-120000)) / 10000.0;
Keep in mind that floating point is not exact. Depending upon your ranges, it is
very possible to get a random number that isn't the exact number of decimal
places you want.
Thanks for the help guys, I was able to do just what I needed. I'll certainly save these formulas for future interest.
Topic archived. No new replies allowed.