rand() function in C return the same value

I have written a simple code with C

#include <stdio.h>
#include <stdlib.h>
int main()
{
int val = rand();
printf("val = %d",val);
}

and I have written a simple bash (to compile and execute the past C programme)

gcc test.c
gcc -o test test.c
./test

the problem is when ever I execute the bash it always returns the same value :val = 1804289383 How can I make it return random values as expected ??

Answers


Given the same starting point, repeated calls to rand will always generate a predictable stream of values. The way you change this is by seeding the generator with a value which varies. You do this by calling srand.

Assuming you don't need to run your program more than once a second, the current time would be a cheap/easy way of choosing a seed.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
    srand(time(NULL));
    int val = rand();
    printf("val = %d\n",val);
}

I've made another small change to your program. Output is sometimes line buffered so I've added a newline \n character to the end of your printf string.


Need Your Help

login function rendering first letter only

php function session login user

I have just made the login function and it is working alright;

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.