dimanche 22 mars 2020

C random integer generator question (A book on C 4th Edition)

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

int main(void)
{
   int i, n;

   printf("\n%s\n%s",
     "Some randomly distributed integers will be printed.",
     "How many do yo want to see? ";
   scanf("%d", &n);
   for (i = 0; i < n; ++i) {
     if (i % 10 == 0)
       putchar('\n');
     printf("%7d", rand());
   }
   printf("\n\n");
   return 0;
}

this is the code from the textbook "A book on C".

when you type 23 when prompted it is supposed to generate 23 random numbers in 3 rows, 8 columns (3*8-1).

i learned that printf("%7d", rand())is supposed to return a value printed in a format of a decimal integer and the width of the field where the integer gets printed is 7.

however, I am getting random numbers that are in a width of more than 7 and it doesn't look neat at all. (no columns nor rows, just a huge chunk of consecutive numbers like 1235289043528935294835698246182965982)

I thought it has something to do with the expression printf("%7d", rand()) function and the way how it is supposed to return values.

I'm starting to think that the textbook is wrong.




Aucun commentaire:

Enregistrer un commentaire