Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Random number from 1 to 9

Posted on 2004-09-20
5
Medium Priority
?
1,255 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 375 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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

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…
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 and use conditional statements in the C programming language.

705 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