Author Topic: Generating and using random numbers  (Read 11959 times)

playerzero

  • Jr. Member
  • **
  • Posts: 15
    • View Profile
Generating and using random numbers
« on: June 09, 2015, 02:57:31 AM »
Hi guys

I'm having trouble working with some random numbers I'm trying to use.
Here is my code:

function irand(max)
{
    local roll = (1.0 * rand() / RAND_MAX) * (max + 1)
    return roll.tointeger()
}

local finform = irand(4);
   if ( finform = 1 ) finalform.file_name = "1.png" ;
   if ( finform = 2 ) finalform.file_name = "2.png" ;
   if ( finform = 3 ) finalform.file_name = "3.png" ;
   if ( finform = 4 ) finalform.file_name = "4.png" ;
   fe.add_text ( finform, 10, 400, 320, 16 );

From what I can tell, it ALWAYS comes up with 4

Can anyone help me debug?

Also one other side point: The add_text at the end is just for debugging, but it doesn't place it at 10, 400, it places it at 0,0 for some reason (I suspect to do with the way the number is formatted).

liquid8d

  • Global Moderator
  • Sr. Member
  • *****
  • Posts: 442
    • View Profile
Re: Generating and using random numbers
« Reply #1 on: June 09, 2015, 04:47:02 PM »
Try these:
Code: [Select]
    function random(minNum, maxNum) {
        return floor(((rand() % 1000 ) / 1000.0) * (maxNum - (minNum - 1)) + minNum);
    }
    function randomf(minNum, maxNum) {
        return (((rand() % 1000 ) / 1000.0) * (maxNum - minNum) + minNum).tofloat();
    }

randomf if you want a float of course ;)

I think yours you need to .tofloat() a number - I think just multiplying by 1.0 doesn't do it.. I can't recall exactly but it is kind of funky :)