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.

Recommended Answers

All 3 Replies

Why not simplify things? num=rand()%(max+1);

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.