Despite having set srand() only once as pointed by similar Q/A about rand()
I think the following rand does not return a value for my customized random function.
Anyway my purpose was to generate a few random numbers
and right after their appearance to count +1 at an array (to calculate their frequency later on)
One represents (5x)+1 at freq[] array
I have read documentation about rand()/srand but I cant figure out the error.
Thanks for your patience!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 1000
int RandomInteger(int low , int high);
main()
{
int freq[9]={0},i,j,number,div;
srand((int)time(NULL));
for(i=0;i<N;i++)
number=RandomInteger(1,9);
switch(number){
case 1:
freq[0]+=1;
break;
case 2:
freq[1]+=1;
break;
case 3:
freq[2]+=1;
break;
case 4:
freq[3]+=1;
break;
case 5:
freq[4]+=1;
break;
case 6:
freq[5]+=1;
break;
case 7:
freq[6]+=1;
break;
case 8:
freq[7]+=1;
break;
case 9:
freq[8]+=1;
break;
default:
;
}
for(i=0;i<9;i++){
div=freq[i]/5;
printf("%d|",div);
for(j=0;j<div;j++)
printf("*");
printf("\n");
}
}
int RandomInteger(int low , int high)
{
int k;
double d;
d=(double)rand()/((double)RAND_MAX+1);
k=(int)(d*(high-low+1));
return low+k;
}
You problem is this:
for(i=0;i<N;i++)
number=RandomInteger(1,9);
It should have
for(i=0;i<N;i++) {
number=RandomInteger(1,9);
..
..
}
Otherwise it runs it N times (same line), but never goes to the switch
until it finishes the loop