dimanche 1 novembre 2020

Why rand() produce negative numbers when it shoudln't?

I tried out this program while learning a course on C.

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

#define MAXVAL 10000
#define MINVAL 1000
#define RANGE MAXVAL-MINVAL
#define RANDVAL (rand()%RANGE)+MINVAL

#define LOAD for(int i=0;i<1000;i++)  \
            { \
                dat[i]=RANDVAL; \
                if(dat[i]<MINVAL)i--;   \ //I have to add this to prevent negative numbers
            }

#define PRINT for(int i=0;i<1000;i++) \
                {\
                    printf("%d\t",dat[i]);  \
                    if((i+1)%10==0)printf("\n");    \
                }

int main()
{
    int dat[RANGE];
  //  printf("%d",RAND_MAX);
    srand(time(0));
    LOAD
    PRINT
    return 0;
}

rand() should produce only 0 to rand_max right? but it produces negative numbers here. What am I doing wrong? Also, saw RAND_MAX to be just 32767. In this era of 64 bit computers, is it right?




Aucun commentaire:

Enregistrer un commentaire