Jump to content

Generate random number


Recommended Posts

Posted

i'm trying to fix a function i had working fine under windows, but in linux doesn't work

int RandomNum() { 
int chosen;
chosen=int(1000*rand()/(RAND_MAX+1.0));
return chosen; 
}

This function under windows (mangos compiled with vs2010) generates a random number between 0-1000, but under linux it returns always 0.

I also have tried this modification with no luck:

srand((unsigned)time(0));
int RandomNum() { 
int floor = 0, ceiling = 1000, range = (ceiling - floor);
int chosen = floor + int((range * rand()) / (RAND_MAX + 1.0));
return chosen;
}

I have tried several things but i don't achieve to get it working, could you help me?

Thanks!

Posted

Hello,

this produces random numbers between 1 and 1000

#include <iostream>
#include <cstdlib>
#include <time.h>

int main()
{
   int chosen;
   srand(time(NULL)); //makes it random

   chosen=rand() % 1000+1;  //range 1000 and 1
   std::cout << chosen;
}

Regards

Skirnir

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue. Privacy Policy Terms of Use