lundi 16 décembre 2019

Weird result from random character generator in C

I am trying to write a program in C that spits out random characters. Following instructions I found here, I wrote this program.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


int main(void) {
   srandom((unsigned) time(NULL));
   printf("Tests various aspects of random\n");
   char misc;
   int num, index;
   printf("Enter number of chars: ");
   scanf("%d", &num);
   printf("\n");

   for (int i = 0; i < num; i++) {
      index = random() % 26;
      misc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[index];
      printf("%d:%s\n", index, &misc);
   }
}

However, it doesn't behave as I expect. When entering a small number of characters for it to generate, like 10, it makes the expected output.

My expected output is a set of

rand_int:char

pairs printed to the screen.

Here is an example of normal operation

Tests various aspects of random
Enter number of chars: 
7:H

4:E

23:X

2:C

4:E

17:R

22:W

11:L

9:J

4:E

However, if I input a large value such as 100, it outputs very strange things like:

Tests various aspects of random
Enter number of chars: 
18:Sd
3:Dd
21:Vd
10:Kd
19:Td
19:Td
14:Od
7:Hd
15:Pd
22:Wd
24:Yd
22:Wd
12:Md
[rest omitted for brevity...]

So the question is, why does it behave this way? What might be a better approach to avoid this?




Aucun commentaire:

Enregistrer un commentaire