How do I generate a random float/decimal?

This is a discussion on How do I generate a random float/decimal? within the C++ Programming forums, part of the General Programming Boards category; Any ideas?...

  1. #1
    Registered User
    Join Date
    Aug 2002
    Posts
    57

    How do I generate a random float/decimal?

    Any ideas?
    "A Programmer being told to 'go to' hell sees the 'go to' part of the sentence as the worst part." - Master Foto

  2. #2
    Registered User
    Join Date
    Dec 2001
    Posts
    88
    Just an idea:

    float f=rand()/100.0;
    Hope you don't mind my bad english, I'm Austrian!

  3. #3
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    This works. I just wrote it now so it isn't the best, plus it is kinda expensive.

    Code:
    #include <iostream>
    #include <cstdlib>
    #include <math.h>
    #include <time.h>
    
    int main(void) {
    	using namespace std;
    	srand(time(NULL));
    	float r;
    	int i;
    	
    	for(;;) {
    		i = rand();
    		r = (i-sqrtf(i))/10000;
    		cout << r << endl;
    	}
    		
    
    	return 0;
    }
    [edit]
    stupid smilies...
    [/edit]

  4. #4
    Just a Member ammar's Avatar
    Join Date
    Jun 2002
    Posts
    953
    Just make a random integer then devide it by another number.
    Then you can store it in a float or double...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how do I generate a random number? (easily?)
    By fsx in forum C Programming
    Replies: 7
    Last Post: 05-12-2009, 06:04 AM
  2. Another brain block... Random Numbers
    By DanFraser in forum C# Programming
    Replies: 2
    Last Post: 01-23-2005, 05:51 PM
  3. Generate random numbers in Lucky7 project using C#
    By Grayson_Peddie in forum C# Programming
    Replies: 1
    Last Post: 04-12-2003, 12:03 AM
  4. Ask about generate Random number
    By ooosawaddee3 in forum C Programming
    Replies: 2
    Last Post: 07-01-2002, 05:30 AM
  5. Best way to generate a random double?
    By The V. in forum C Programming
    Replies: 3
    Last Post: 10-16-2001, 05:11 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21