How to generate a random generator in C?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Ruhi22
    New Member
    • Sep 2008
    • 1

    How to generate a random generator in C?

    I am trying to use the default random generator in C.
    the funcion rand() is fine but when tried 'srand(time(0))' it is giving me the following error:


    error C3861: 'time': identifier not found




    the code I am tryin it in is as follows:

    #include <stdio.h>
    #include <stdafx.h>
    #include <iostream>
    #include <stdlib.h>


    int main(void)
    {
    int i, m, x[100];

    printf("\n\nEnt er the length of the array: ");
    scanf_s("%d", &m);

    for(i=0; i<m; i++) x[i]=0;

    for(i=0; i<m; i++) x[i]=srand(time(0)) ;

    printf("\n\n");
    for(i=0; i<m; i++) printf(" %d", x[i]);
    printf("\n\n");
    }
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    You have to include another header file: <time.h> if you want to use the time() function.

    kind regards,

    Jos

    Comment

    • Tassos Souris
      New Member
      • Aug 2008
      • 152

      #3
      Let me tell you one interesting thing about srand

      When you call srand again with the same seed value then the exact same sequence of pseudo-random integers in range 0 to RAND_MAX shall be repeated.

      I think this may help you in debugging and see what is the behavior of your program under the same conditions.

      With respect,

      Tassos Souris

      Comment

      • sicarie
        Recognized Expert Specialist
        • Nov 2006
        • 4677

        #4
        Small notes on style:

        If you are using C, you can remove the declaration of the C++ header 'iostream'. That may cause issues later on.

        Also, best practice is considered to use 'int main()' and then show a return value at the end of your program that will declare if the program completed successfully or not.

        Did using Jos' selection of including time.h fix the error?

        Comment

        • donbock
          Recognized Expert Top Contributor
          • Mar 2008
          • 2427

          #5
          1. I suggest the argument to time() be NULL rather than 0.
          2. I suggest that you explicitly cast the time() return value to unsigned int.

          See below. I have repeated the prototypes for the library functions for your reference, but you should accomplish the same by including the appropriate header files.
          Code:
          /* FYI: prototypes for the standard library functions */
          void srand(unsigned int seed);
          time_t time(time_t *timer);
          
          srand( (unsigned int)time(NULL) );

          Comment

          Working...