Random Integers and Decimals

Sep 2, 2011 at 11:40pm
Is it possible to get C++ to give me a random number that can either be an integer or a decimal. For instance: 12, 76.5, 50.2, 89, etc.

Thanks
Sep 2, 2011 at 11:42pm
If you want e.g. one decimal, increase your range and then divide by 10.0
Sep 2, 2011 at 11:44pm
Use rand() and divide by by 10.0 and place into a float.
Sep 3, 2011 at 7:00am
Thanks for the replies.

MY max is 14400 but whenever I run the program the number isn't very random.
For instance I might get 10020 as my random number. If I close the program and run it again right after then number is then around 10040. Is there a way that I could get the numbers to be more random? Thanks.
Sep 3, 2011 at 7:08am
are you seeding the random function?
Sep 3, 2011 at 7:48am
closed account (Gz64jE8b)
Esanders323, before you use your rand() function have this in your code:

srand(time(NULL));

This'll give you the random numbers you want.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

using namespace std;

int main()

{
    int a = rand();
    cout << a;
    system("pause");
    return 0;
}


Gives me 41 every time I run it.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

using namespace std;

int main()

{
    srand(time(NULL));
    int a = rand();
    cout << a;
    system("pause");
    return 0;
}


Gives me a totally different number every time I run it.
Last edited on Sep 3, 2011 at 7:51am
Sep 3, 2011 at 4:15pm
I am seeding it, however, the number still isn't very random.

I tried the above code (the correct one) and got 10244 my first run. I closed the program and ran it agin. My next number was 10266, then 10294, then 10314, and I assuming my next number would have been around 10330.

The numbers just aren't very random, I can usually guess within 10 what the next number will be.
Sep 3, 2011 at 4:18pm
how about trying 10 numbers in same program... just test :P

rand() is AFAIK another XOR randomizer which NEEDS seed to start the "real" random
Last edited on Sep 3, 2011 at 4:19pm
Sep 3, 2011 at 4:43pm
closed account (Gz64jE8b)
Esanders323, consider this program it performs several calculations on the number to make it truly random.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <windows.h>


using namespace std;

int main()

{

int a, b, c, lolrand;
srand(time(NULL));
a = rand();
lolrand = rand() % 10 + 1;
b = ((a*a) / (lolrand));
srand(b);
c = rand();
cout << c;
cout << "\n\n";

system("PAUSE");
return 0;

}


Just note that rand(); ALWAYS works better with smaller numbers.

Edit: Yes that IS variable called 'lolrand' I'm really that cool.
Last edited on Sep 3, 2011 at 4:43pm
Topic archived. No new replies allowed.