Pergunta

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;
}
Foi útil?

Solução

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

Outras dicas

In your code high is set to 1 and low is set to 9 this will result in a negative k. The return will be outside of the range of your cases and will fall to default.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top