• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1261
  • Last Modified:

Random number from 1 to 9

I need to generate numbers from 1 to 9. How should i write it, what header file i should use?
0
HonAlan
Asked:
HonAlan
1 Solution
 
sunnycoderCommented:
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
 
PaulCaswellCommented:
Sunnycoder is right! .... This time ;)
0
 
tzxie2000Commented:
#include <math.h>

and read rand/randomize function's descripe carefully and you can get any random number
0
 
sunnycoderCommented:
lol, thanks Paul
0
 
koposCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get 10% Off Your First Squarespace Website

Ready to showcase your work, publish content or promote your business online? With Squarespace’s award-winning templates and 24/7 customer service, getting started is simple. Head to Squarespace.com and use offer code ‘EXPERTS’ to get 10% off your first purchase.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now