# Thread: Random array generator for floats

1. ## Random array generator for floats

Hi. I have come up with this for a random array generator for integers, but i can't seem to get to get it to work with floats. I changed some of the variables to floats but it didn't work. any ideas?

Code:
```#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main ()
{
int i;
unsigned int iseed = (unsigned int)time(NULL);
srand (iseed);

for (i=0; i<5; i++)
{
printf ("rand[%d]= %u\n",i, rand ());
}
return 0;
}``` 2. Take it in three parts:

1) generate and assign a random integer to the digits on the left side of the decimal point.

2) generate and assign the digits on the right hand side of the decimal of the float

3) generate and assign a positive or negative sign to the number, if needed. 3. Or if you look up the range of random integers that rand() generates, you may just want to divide the result by some constant.

For example: rand() / 1000.0 4. If you want a particular range of float/double values, say from 30 to 90, you could do something like:
Code:
```double rand_value;

rand_value = (double)rand() / RAND_MAX;  // generate a random number between 0 and 1
rand_value *= (high - low);  // scale it to fit between high and low, range now from 0 to high-low
rand_value += low;  // offset it by low, range now from low to high

/* same thing in one statement */
rand_value = ((double)rand() / RAND_MAX) * (high - low) + low;``` 5. Hi,

Thanks for the reply's have I have divided the rand() by a constant and it seems to work well. My question now is how can I access the array. would the array be rand[]? 6. You would access the array as usual. One problem now is that your code does not actually assign the numbers generated to the elements of an array. 7. That's what i was thinking. It prints out like so:

rand = floating point number 1
rand = floating point number 2
rand = floating point number 3
rand = floating point number 4

I have to work out some way of assigning arrayname = floating point number 1 8. Originally Posted by tomelk31 That's what i was thinking. It prints out like so:

rand = floating point number 1
rand = floating point number 2
rand = floating point number 3
rand = floating point number 4

I have to work out some way of assigning arrayname = floating point number 1
Giving an array (or other variable) the same name as a function can be problematic. You should pick a different name for the array... randnum[] or such... Popular pages Recent additions 