Solved

Random number from 1 to 9

Posted on 2004-09-20
5
1,252 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.

739 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