0

Hi I'm trying to generate a random number betwen any numbers (eg from 1 to 100) and I've tried this code:

#include<stdio.h>
#include<math.h>
#include<time.h>
#include <stdlib.h>
int NumAleatori(int max)
{
      int num;
      num=((int)ceil(((double)rand()/RAND_MAX)*(max+1)))%(max+1);
      return num;
}
void main ()
{
      int N,a;
      srand( (unsigned)time( NULL ) );
      printf(“Enter an integer:\”);
      scanf(“%d”,&N);
      a = NumAleatori(N);
      printf(“%d”,a);
     
}

It does not give me random numbers. It gives me the same number for small ranges and it follows a pattern for a graters ranges.

4
Contributors
3
Replies
4
Views
8 Years
Discussion Span
Last Post by nucleon
0

In num=((int)ceil(((double)rand()/RAND_MAX)*(max+1)))%(max+1); You are dividing and modding at the same time.
You need to choose one or the other.
With division (and floats): num = (int)(((double)rand() / (RAND_MAX + 1)) * max); or with modding (and ints) num = rand() % max; These both give between 0 (incl.) and max (excl.).
If you want 1 to max (both incl.), add + 1 to the very end of either.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.