/* * program to show random number generation * prints the number of random numbers indicated by command line argument * * Matt Bishop, ECS 36A, Fall Quarter 2019 */ #include #include #include /* * function prototypesl shoulkdbe declared nb stdlib.h but aren't */ void srandom(unsigned int); long random(void); /* * main routine */ int main(int argc, char *argv[]) { int i; /* counter in a for loop */ int n; /* value of command line argument */ long int prn; /* pseudorndom number */ char *aend; /* points just beyond where number found */ time_t t; /* current time; used to seed the PRNG */ /* * check there is a second argument */ if (argc != 2){ fprintf(stderr, "Usage: %s number\n", argv[0]); return(1); } /* * convert that to an integer and check for error */ n = strtol(argv[1], &aend, 10); if (*aend != '\0'){ /* extra stuff at the end */ fprintf(stderr, "Usage: %s number\n", argv[0]); return(1); } /* it's a number -- be sure it's positive */ if (n <= 0){ fprintf(stderr, "A *positive* integer please!!!\n"); return(1); } /* * now we know how many pseudorandom numbers to print * * next, seed the pseudorandom number generator (PNRG) */ if ((t = time(NULL)) == -1){ perror("time"); return(1); } srandom((unsigned int) t); /* * generate and print them */ printf("First column is number from random()\n"); printf("Second column is a random number between 0 and 99 inclusive\n"); printf("Third column is a random number between -50 and 50 inclusive\n"); for(i = 0; i < n; i++){ prn = random(); printf("%10ld\t%3ld\t%3ld\n", prn, prn % 100, prn % 101 - 50); } /* * bye! */ return(0); }