Hi, I need help with a simple problem. I'm still new to c++ but this should be fairly straightforward. I just need to generate a random number, but with only a very small range like ... 0.00001 to 0.001. Any help would be appreciated. Thanks.

Recommended Answers

All 2 Replies

This should do it:

#include "stdafx.h"
#include <iostream> 
#include <ctime> 
#include <cstdlib>

using namespace std;

int main() 
    double random_integer; 
    double lowest=0.00001, highest=0.00100; 
    double range=(highest-lowest)+0.00001; //here you must add the lowest of your numbers
    for(double index=0; index<1; index++){ //you can generate as many numbers you want, just replace index<1 with index<x where x is the number of random numbers you want
        random_integer = lowest+double(range*rand()/(RAND_MAX + 1.0)); 
        cout << random_integer << endl; 

Hope I help :)

In line 13 you mustn't add lowest and index variable should be integer (you could get some nasty rounding errors, maybe not in this example, but also it will be faster). This is not so important, but random_integer is bad variable name. You can also look into http://www.boost.org/doc/libs/1_45_0/doc/html/boost_random.html , it will be part of new c++ standard.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.