We help IT Professionals succeed at work.

# C Random Numbers 0.0 to 1.0

on
Medium Priority
382 Views
Hi,
I need to generate random numbers using C in the following range:
0.0 <= X <= 1.0

That will give us the following possible values
0.0
0.1
0.2
...
0.9
1.0

So far, I have been able to generate random numbers, but not to the tenth place.  If anyone knows how to modify my code, or write better code, that is what I need.  Here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
int main() {
srand(time(NULL));

double rnum;
int i;

for(i=0; i<=20; i++) {
rnum = 1.1 * (float) rand() / (float) RAND_MAX;
printf("Number: %lf\n", rnum);
}

return 0;
}

Comment
Watch Question

## View Solutions Only

Commented:
>>rnum = 1.1 * (float) rand() / (float) RAND_MAX;
rnum = (float)(rand() % 11) /10;

~marchent~

Not the solution you were looking for? Getting a personalized solution is easy.

Commented:
marchent,

That worked perfect, except my printf line still outputs the extra 0's.  Is there a way to get rid of them?  For example:

0.600000
1.000000
0.200000

Thanks
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015
Commented:
printf("Number: %.1f\n", rnum);

Commented:
Ozo,
Sorry for the confusion.  I meant get rid of the extra 0's so the number stored is X.X  not X.XXXXXX.  However, your printline shows the results I need, but doesn't store the ones I need.

Thanks
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015

Commented:
I'm sorry, I don't understand what you mean when you say the number stored is X.X  not X.XXXXXX
the number is not stored as a string of ASCII digits, the number is stored as a float,
which probably does not even have an exact representation for 0.1
##### Thanks for using Experts Exchange.

• View three pieces of content (articles, solutions, posts, and videos)
• Ask the experts questions (counted toward content limit)
• Customize your dashboard and profile