Solved

Random number from 1 to 9

Posted on 2004-09-20
5
1,246 Views
Last Modified: 2010-04-15
I need to generate numbers from 1 to 9. How should i write it, what header file i should use?
0
Comment
Question by:HonAlan
5 Comments
 
LVL 45

Accepted Solution

by:
sunnycoder earned 125 total points
ID: 12100799
Hi HonAlan,

use rand function
it is generally defined in stdlib.h
use srand to seed the rand function
refer to their man pages for help

num=rand()%9 +1 should give you what you want

Sunnycoder
0
 
LVL 16

Expert Comment

by:PaulCaswell
ID: 12101519
Sunnycoder is right! .... This time ;)
0
 
LVL 5

Expert Comment

by:tzxie2000
ID: 12102854
#include <math.h>

and read rand/randomize function's descripe carefully and you can get any random number
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 12109326
lol, thanks Paul
0
 
LVL 1

Expert Comment

by:kopos
ID: 12366393
Hi HonAlan,
Actually rand() returns a float value. So rand()%9 will mostly always be equal to 0.00 ( a float moded with an integer always equals a zero).

The solution i prefer using is

#include<math.h>
srand(time(null));
rand_num = (int)((rand()%RAND_MAX)*9.0) + 1;
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now