CCS C Software and Maintenance Offers
FAQFAQ   FAQForum Help   FAQOfficial CCS Support   SearchSearch  RegisterRegister 

ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

CCS does not monitor this forum on a regular basis.

Please do not post bug reports on this forum. Send them to support@ccsinfo.com

Random Number between a range?

 
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion
View previous topic :: View next topic  
Author Message
Chantry



Joined: 18 Jan 2011
Posts: 13

View user's profile Send private message

Random Number between a range?
PostPosted: Mon Feb 07, 2011 6:37 pm     Reply with quote

Hi,

I found this code:
Code:
char random_byte;

char rand(void)   {
   char sum;
   
   sum = 0;
   
   // This calculates parity on the selected bits (mask = 0xb4).
   if(random_byte & 0x80)
      sum = 1;
   
   if(random_byte & 0x20)
      sum ^= 1;
   
   if(random_byte & 0x10)
      sum ^= 1;
   
   if(random_byte & 0x04)
      sum ^= 1;
   
   random_byte <<= 1;
   
   random_byte |= sum;
   
   return(random_byte);
}

void srand(char seed) {
   random_byte = seed;
}


I want wondering if it is possible to generate a number between a specific range? Say for example, I want a random number between 0-20, is this possible, or do I have to keep generating random numbers until I find one which is in range?

Regards,

James
PCM programmer



Joined: 06 Sep 2003
Posts: 21708

View user's profile Send private message

PostPosted: Mon Feb 07, 2011 8:30 pm     Reply with quote

That function was posted in the early years of the compiler, before CCS
added the standard rand() function. You don't need to use it now.

You can generate random numbers with the rand() function, and set the
maximum value generated by defining the RAND_MAX value.
Read these threads:
http://www.ccsinfo.com/forum/viewtopic.php?t=28834
http://www.ccsinfo.com/forum/viewtopic.php?t=42025

To change RAND_MAX to a different value while the program is running,
see this thread:
http://www.ccsinfo.com/forum/viewtopic.php?t=43069
Chantry



Joined: 18 Jan 2011
Posts: 13

View user's profile Send private message

PostPosted: Tue Feb 08, 2011 5:24 am     Reply with quote

Thank you very much, I did search but couldn't find those mentioned threads.
Display posts from previous:   
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group