www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2000/08/17/11:15:24

From: "Rafał Maj" <r_maj AT poczta DOT onet DOT pl>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Random numbers
Date: Thu, 17 Aug 2000 17:10:05 +0200
Organization: Academic Computer Center CYFRONET AGH
Lines: 31
Message-ID: <8ngvdi$5n1$1@info.cyf-kr.edu.pl>
References: <8ngtjq$cn1$1 AT news DOT clinet DOT fi>
NNTP-Posting-Host: d-94-53-08.cyfronet.krakow.pl
X-Trace: info.cyf-kr.edu.pl 966525170 5857 149.156.1.168 (17 Aug 2000 15:12:50 GMT)
X-Complaints-To: news AT cyf-kr DOT edu DOT pl
NNTP-Posting-Date: 17 Aug 2000 15:12:50 GMT
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 5.00.2615.200
X-MimeOLE: Produced By Microsoft MimeOLE V5.00.2615.200
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

User <dots AT hotmail DOT comPOF> wrote
> How can i make a function
> that gives a random number in different ranges?
> Eg. Rand(Min,Max)
> would give a random number between Min and Max.

If You want only to have only integer numbers :
  int rnd(int min, int max) { return (random() % (max-min+1)) + min; }

If You alsow want use float, then ther is whole program :

#include <iostream.h>
#include <stdlib.h>
#include <math.h>
float rnd_one() { return (random()%10001)/10000.0; } // helper function
float rnd_float(float min, float max) {
  float f = (rnd_one()/10000.0 + rnd_one() + rnd_one()*10000);
  return fmod(f,max-min) + min;
}

main() {
  cerr<<"Integer : "<<endl;
  for (int i=0; i<25; i++) cerr << rnd(5,10) << endl;
  cerr<<"\n\nFloat : "<<endl;
  for (int i=0; i<100; i++) cerr << rnd_float(1.50, 1.60) << endl;
}

Rafal


- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019