0

I am working on calculator application. For me all operations are cleared except "rand". Could any one tell me how to generate random number of some number by selecting rand.

For example initially i select one(1) then rand... if so it has to be displayed random number of one(1).

ram
  • 107
  • 1
  • 2
  • 11
  • 1
    Check this link. Its already there. http://stackoverflow.com/questions/160890/generating-random-numbers-in-objective-c – Teja Mar 13 '12 at 13:33

3 Answers3

2

In objective-C you should use (for between 0 and 1)

int r = arc4random() % 10;

float r2 = r/10

Imagine that you want a number between 0 and 50 with decimals, then you should do:

int r = arc4random()%50*100;
float r2 = r/100;

You will get something like 40.123

Antonio MG
  • 20,382
  • 3
  • 43
  • 62
  • Its impossible, I just tried this: int r = arc4random() % 3; and its giving mew numbers like 2, 1, etc.. – Antonio MG Mar 13 '12 at 13:53
  • Yeah its giving random numbers but i want that random number in between 0 to 1 only . Thanking you – ram Mar 13 '12 at 14:04
  • whatever number i may give it has to display random number in between 0 and one only – ram Mar 13 '12 at 14:14
  • I dont understand, my code is giving you a random number between 0 and 1! – Antonio MG Mar 13 '12 at 14:14
  • Sorry for keep on disturbing u and depending up on u ... could u check my following code if ([str isEqualToString:@"rand"]) { int x = [currentVal intValue]; double randomNumber = arc4random()%x; NSLog(@"%f",randomNumber); } – ram Mar 13 '12 at 14:18
  • What I understand is that you want a random number between 0 and X With decimals? – Antonio MG Mar 13 '12 at 14:19
  • yeah ... BUt not knowing how to do – ram Mar 13 '12 at 14:28
  • Thank you for your explanation.. But it has to generate as 0.4523204802 or 0.24992334234 and so on – ram Mar 13 '12 at 14:32
0

NSInteger num = (arc4random() % maxnumber) + 1;

glogic
  • 4,042
  • 3
  • 28
  • 44
0

Check the synopsis...

LIBRARY Standard C Library (libc, -lc)

SYNOPSIS #include

 u_int32_t
 arc4random(void);

 void
 arc4random_stir(void);

 void
 arc4random_addrandom(unsigned char *dat, int datlen);

DESCRIPTION The arc4random() function uses the key stream generator employed by the arc4 cipher, which uses 8*8 8 bit S-Boxes. The S-Boxes can be in about (2*1700) states. The arc4random() function returns pseudo- random numbers in the range of 0 to (2*32)-1, and therefore has twice the range of rand(3) and random(3).

 The arc4random_stir() function reads data from /dev/urandom and uses it to permute the S-Boxes via
 arc4random_addrandom().

 There is no need to call arc4random_stir() before using arc4random(), since arc4random() automatically
 initializes itself.

EXAMPLES The following produces a drop-in replacement for the traditional rand() and random() functions using arc4random():

       #define foo4random() (arc4random() % ((unsigned)RAND_MAX + 1))
Teja
  • 13,214
  • 36
  • 93
  • 155