ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Hi. As a programming practice I am going to be making a simple text based game similiar to dungeons and dragons. I will need random numbers for damage from attacks, etc. Will using >
result = 1 + rand() % 20
give me a good result for say a number from 1-20?
Or is there a better way to get a random number then using rand()?
In Numerical Recipes in C: The Art of Scientific Computing
(William H. Press, Brian P. Flannery, Saul A. Teukolsky,
William T. Vetterling; New York: Cambridge University
Press, 1992 (2nd ed., p. 277)), the following comments are
made:
"If you want to generate a random integer between 1
and 10, you should always do it by using high-order
bits, as in
#include<stdio.h>
int main()
{
int ix;
srand(); //seed for random number generator
for ( ix = 0; ix < 50; ++ix)
printf("%d\n", rand() % 20 + 1);
return 0;
}
I tested this and it worked, but there are better algorithms. This is the basic way to get a random number using the standard C library. Read the Link page for more information.
< http://www.mkssoftware.com/docs/man3/srand.3.asp >
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.