Solved

Random number from 1 to 9

Posted on 2004-09-20
5
1,247 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

Free camera licenses with purchase of My Cloud NAS

Milestone Arcus software is compatible with thousands of industry-leading cameras for added flexibility. Upon installation on your My Cloud NAS, you will receive two (2) camera licenses already enabled in the software. And for a limited time, get additional camera licenses FREE.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
How to organize data in excel ? 2 112
Which version of C should I use when Perl is too slow? 13 172
Passing command line arguments in C 10 85
Detect CR LF to each line 12 152
Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
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…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops 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.

914 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

19 Experts available now in Live!

Get 1:1 Help Now