Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1258
  • 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

Featured Post

Independent Software Vendors: 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!

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