Thread: Rand() won't be random

  1. #1
    Registered User
    Join Date
    Sep 2005

    Rand() won't be random

    #include <cstdlib>
    using namespace std;
    int main() {
    int guess, secretnumber;
    secretnumber = rand();
    cout << "Guess the number: ";
    cin >> secretnumber;
    if (guess = secretnumber)
    cout << "You guessed it!";
    else if(guess > secretnumber)
    cout << "You're to high!";
    else if(guess < secretnumber) 
    cout << "You're to low!";
    return 0;

    When I run it, I guess it every time for some reason, and I don't think it is being random. Please tell me if this code is correct, I've been fooling around for a while, and my book I don't think is very current (not by years, but some things are off, for instance when I try the gets(); code to input a string into an array, the compiler just skips over it and goes to the next statement, I noticed that the cin function thingy stops the thing while until you type something in an hit enter, but gets() does not do this.

  2. #2
    Registered User
    Join Date
    Jan 2005
    You have to call srand() once at the start of your program to seed the random number generator. Usually people use srand(time(0)) to use the current time so that the seed will be different each time you run the program and the random numbers will be more random. You have to #include <ctime> to use time().

    Also, remember the difference between = and ==, and pay attention to which variables you use where.

  3. #3
    Registered User
    Join Date
    Mar 2006
    rand() doesn't produce TRUE random numbers, because there isn't a block of depleted uranuim in your CPU; if there is please call your PC vendor Instead it uses a number called the "seed" and a simple formula to generate numbers based on the seed. Most rand() implementations start off with the same seed every time, like 0 or 1. srand() with a random value will make rand() produce a different string of numbers.
    #include <stdio.h>
    void J(char*a){int f,i=0,c='1';for(;a[i]!='0';++i)if(i==81){
    /3*3+f/3*9+f%3]==c||a[i%9+f*9]==c||a[i-i%9+f]==c)goto e;a[i]=c;J(a);a[i]
    ='0';e:;}}int main(int c,char**v){int t=0;if(c>1){for(;v[1][
    t];++t);if(t==81){J(v[1]);return 0;}}puts("sudoku [0-9]{81}");return 1;}

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. random to int?
    By psyadam in forum C# Programming
    Replies: 7
    Last Post: 07-22-2008, 08:09 PM
  2. Lesson #3 - Math
    By oval in forum C# Programming
    Replies: 2
    Last Post: 04-27-2006, 08:16 AM
  3. Another brain block... Random Numbers
    By DanFraser in forum C# Programming
    Replies: 2
    Last Post: 01-23-2005, 05:51 PM
  4. How do I restart a random number sequence.
    By jeffski in forum C Programming
    Replies: 6
    Last Post: 05-29-2003, 02:40 PM
  5. Best way to generate a random double?
    By The V. in forum C Programming
    Replies: 3
    Last Post: 10-16-2001, 04:11 PM