473,750 Members | 2,265 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why will this not generate a random number!?

This has been driving me crazy. I've done basic C in school, but my
education is mainly based on object oriented design theory where Java
is our tool. For some reason, while helping a friend with a C
Programming lab. I cannot for the life of me generate a random number.
i don't know what is wrong. please help.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define RAND_MAX 32768

int main(void)
{
float b;

b = ((float)rand()/RAND_MAX);
printf("Random Number: %f", b);

system("PAUSE") ;
return 0;
}
Nov 14 '05 #1
15 4949
John Cassidy wrote:
This has been driving me crazy. I've done basic C in school, but my
education is mainly based on object oriented design theory where Java
is our tool. For some reason, while helping a friend with a C
Programming lab. I cannot for the life of me generate a random number.
i don't know what is wrong. please help.
rand() will generate spesific "random", se my addition to the code below.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define RAND_MAX 32768

int main(void)
{
float b;
// The function srand() is used to seed the random sequence generated by
// rand(). For any given seed, rand() will generate a specific "random"
// sequence over and over again.
srand(time(NULL ));
b = ((float)rand()/RAND_MAX);
printf("Random Number: %f", b);

system("PAUSE") ;
return 0;
}


If you're on a UNIX system you might want to consider using /dev/urandom
to generate random.

--
Regards
Hans-Christian Egtvedt
Nov 14 '05 #2
jo**********@gm ail.com (John Cassidy) writes:
This has been driving me crazy. I've done basic C in school, but my
education is mainly based on object oriented design theory where Java
is our tool. For some reason, while helping a friend with a C
Programming lab. I cannot for the life of me generate a random number.
i don't know what is wrong. please help.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define RAND_MAX 32768

int main(void)
{
float b;

b = ((float)rand()/RAND_MAX);
printf("Random Number: %f", b);

system("PAUSE") ;
return 0;
}


Thank you for posting a complete program (too many people post
fragments or pseudo-code). But a little more detail on what behavior
you're actually seeing would be helpful. You say it doesn't generate
a random number; what does it do?

You don't need <math.h>; rand() is declared in <stdlib.h>

Don't define RAND_MAX yourself, it's defined for you in <stdlib.h>.

Your output doesn't end in a newline; on systems, this might cause
your output not to appear at all. system("PAUSE") won't work if the
system doesn't have a PAUSE command.

Your system should have documentation on the rand() and srand()
functions. Find it and read it.

I think your actual problem is probably answered by entry 13.17 of the
C FAQ, <http://www.eskimo.com/~scs/C-faq/q13.17.html>. Questions
13.15 through 13.20 deal with random numbers. Read the whole section.
Read the whole FAQ.

If you call rand() without first calling srand(), it's equivalent to
calling rand() after calling srand(1). This always gives you the same
sequence of numbers. On one system I just tried, the first call to
rand() gave me 0.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #3
John Cassidy wrote:
This has been driving me crazy. I've done basic C in school, but my
education is mainly based on object oriented design theory where Java
is our tool. For some reason, while helping a friend with a C
Programming lab. I cannot for the life of me generate a random number.
i don't know what is wrong. please help.
Before we get started here, please note that this is fully covered in
the FAQ, and it is normally accepted practice in newsgroups to check the
FAQ before posting. Before you shout, "But I didn't know there was a
FAQ," note also that it is normally accepted practice to lurk in
newsgroups before posting; many people here have links to the FAQ in
their sigs and, if you had lurked for anything like the expected period,
you would have seen one of the periodic postings of the FAQ itself.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define RAND_MAX 32768
No, you don't do this. RAND_MAX is a macro defined by your implementation.

int main(void)
{
float b;

You ought to, unless you want the same sequence everytime you run the
program, seed the random number generator once with srand() before using
it. See the FAQ for details.
b = ((float)rand()/RAND_MAX);
OK, so you want b in the range [0,1]. Generally, however, you really
want b in the range [0,1):
b = rand()/(RAND_MAX+1.);
printf("Random Number: %f", b);

system("PAUSE") ;
You are getter off not relying on the host system having a command named
"PAUSE".
getchar();
would accomplish the same thing, wouldn't it? return 0;
}

Nov 14 '05 #4
jo**********@gm ail.com (John Cassidy) wrote in message news:<6f******* *************** ****@posting.go ogle.com>...
This has been driving me crazy. I've done basic C in school, but my
education is mainly based on object oriented design theory where Java
is our tool. For some reason, while helping a friend with a C
Programming lab. I cannot for the life of me generate a random number.
i don't know what is wrong. please help.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define RAND_MAX 32768

int main(void)
{
float b;

b = ((float)rand()/RAND_MAX);
printf("Random Number: %f", b);

system("PAUSE") ;
return 0;
}


Try to seed with srand()
Nov 14 '05 #5
In <2u************ *@uni-berlin.de> Martin Ambuhl <ma*****@earthl ink.net> writes:
John Cassidy wrote:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define RAND_MAX 32768


No, you don't do this. RAND_MAX is a macro defined by your implementation.

int main(void)
{
float b;


You ought to, unless you want the same sequence everytime you run the
program, seed the random number generator once with srand() before using
it. See the FAQ for details.
b = ((float)rand()/RAND_MAX);


OK, so you want b in the range [0,1]. Generally, however, you really
want b in the range [0,1):
b = rand()/(RAND_MAX+1.);


Have a closer look at his definition of RAND_MAX. If his implementation
is using a 15-bit generator (like the one shown in the C standard), he is
effectively dividing by RAND_MAX+1 :-)

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #6
In <6f************ **************@ posting.google. com> jo**********@gm ail.com (John Cassidy) writes:
This has been driving me crazy. I've done basic C in school, but my
education is mainly based on object oriented design theory where Java
is our tool. For some reason, while helping a friend with a C
Programming lab. I cannot for the life of me generate a random number.
i don't know what is wrong. please help.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
What did you include <math.h> for?
#define RAND_MAX 32768
If your compiler didn't complain about the redefinition of RAND_MAX, get
a better one. If it did, you have absolutely no excuse for having
ignored it!
int main(void)
{
float b;

b = ((float)rand()/RAND_MAX);
printf("Random Number: %f", b);
Why do you think this number is not random enough? If you want different
numbers on different runs, open your favourite C book and read the
specification of the rand() and srand() functions. Or read the FAQ,
which is a MUST before posting for the first time, anyway.
system("PAUSE") ;
You don't need this crap. If you're using a poorly designed IDE that
closes the program console as soon as the program terminates, getchar()
is the function you want to call here. It is also supposed to fix the
bug in your printf call, which is not terminating the line properly.
return 0;
}


Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #7
Stuart Gerchick wrote:
jo**********@gm ail.com (John Cassidy) wrote in message
This has been driving me crazy. I've done basic C in school, but
my education is mainly based on object oriented design theory
where Java is our tool. For some reason, while helping a friend
with a C Programming lab. I cannot for the life of me generate a
random number. i don't know what is wrong. please help.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define RAND_MAX 32768

int main(void)
{
float b;

b = ((float)rand()/RAND_MAX);
printf("Random Number: %f", b);
system("PAUSE") ;
return 0;
}


Try to seed with srand()


Maybe because he should be using double, not float?

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!

Nov 14 '05 #8
Martin Ambuhl <ma*****@earthl ink.net> wrote:
John Cassidy wrote:
system("PAUSE") ;


You are getter off not relying on the host system having a
command named "PAUSE".
getchar();
would accomplish the same thing, wouldn't it?


Not entirely: "pause" waits for any keypress, whereas getchar()
usually requires the Enter key.
Nov 14 '05 #9
Old Wolf wrote:
Martin Ambuhl <ma*****@earthl ink.net> wrote:
John Cassidy wrote:

system("PAUSE") ;


You are getter off not relying on the host system having a
command named "PAUSE".
getchar();
would accomplish the same thing, wouldn't it?

Not entirely: "pause" waits for any keypress, whereas getchar()
usually requires the Enter key.


Can you really predict with confidence that "pause" works that way on
any platform?
Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
6252
by: vishal | last post by:
i want to generate a random number of a fixed length so how can i do this ?? i know some function which returns a single random character at a time but is there any built-in function which takes length of string and return a random string of that length?????? can i implement mechanism so that the random number generated is form a list of characters i specify. e.g. suppose if i want to create a random
12
5228
by: Jim Michaels | last post by:
I need to generate 2 random numbers in rapid sequence from either PHP or mysql. I have not been able to do either. I get the same number back several times from PHP's mt_rand() and from mysql's RAND(). any ideas? I suppose I could use the current rancom number as the seed for the next random number. but would that really work?
6
2777
by: Anamika | last post by:
I am doing a project where I want to generate random numbers for say n people.... These numbers should be unique for n people. Two people should not have same numbers.... Also the numbers should not be repeted.. Do anyone have some nice algorithm for that? Or anyone can suggest me any type of book or site for that purpose?
3
1464
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - How do I generate a random integer in ? ----------------------------------------------------------------------- function Random(x) { return Math.floor(x*Math.random()) } gives a random number in the range 0..(x-1); `` Random(N)+1 '' for http://msdn.microsoft.com/library/en-us/script56/html/js56jsmthrandom.asp
3
2501
by: td0g03 | last post by:
Like the titles says I'm suppose to generate a random number then divide that by a number inputed by a user. The random number can range from 2-8. I tried to do the code, but I get some weird result here is the result Please enter a number: 18 a. number 18.00 b. the random number 6 00-1.#J << suppose to be 3 , but I get this number. (Trying to get 18 divided by 6. This is the code I have so...
4
10588
by: fatimahtaher | last post by:
Hi, I am supposed to create a program that generates a random number and then asks the user to guess the number (1-100). The program tells the user if he guessed too high or too low. If he guessed right, it asks the user is he/she wants to play again. If the answer is yes, it generates a random number and asks the user to guess the number again. The user can exit if he enters 0. I have created the following code so far but it does not work....
7
2025
by: teh.sn1tch | last post by:
I created a random number generator for an application that uses a MersenneTwister class I found on the net. Basically I generate two random numbers from the MersenneTwister class and use each one as a seed for the built in Random class of the .net framework. To better illustrate I am prodviding the complete code for this application, it isn't too much but I would like to know if this is a viable solution because I am a pretty new to C#...
9
6606
by: Chelong | last post by:
Hi All I am using the srand function generate random numbers.Here is the problem. for example: #include<iostream> #include <time.h> int main() {
3
1987
by: drpertree | last post by:
I'm writing in C. I am trying to get a simple way to generate a random number between 0 and 1. I'm not sure of two things - how to limit a random number to 0 or 1 and how to reset it every time I hit the "Enter" key. I want to try to do something simple like a coin flip. Each time the person presses enter, a random number is generated and if it is 0 it's heads and if 1 it's tails. I'm fairly new at C and am not sure exactly what to...
0
9000
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8838
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9577
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9396
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9339
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8260
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6804
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6081
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4713
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.