Generate Random Numbers Between Two Numbers in Objective-C

后端 未结 6 1740
遇见更好的自我
遇见更好的自我 2020-12-07 19:07

I have two text boxes and user can input 2 positive integers (Using Objective-C). The goal is to return a random value between the two numbers.

I\'ve used \"man arc4

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-07 19:09

    Objective-C Function:

    -(int)getRandomNumberBetween:(int)from to:(int)to
    {
        return (int)from + arc4random() % (to-from+1);
    }
    

    Swift:

    func getRandomNumberBetween(_ from: Int, to: Int) -> Int 
    {
        return Int(from) + arc4random() % (to - from + 1)
    }
    

    Call it anywhere by:

    int OTP = [self getRandomNumberBetween:10 to:99];
    NSLog(@"OTP IS %ld",(long)OTP);
    NSLog(@"OTP IS %@",[NSString stringWithFormat @"%ld",(long)OTP]);
    

    For Swift:

    var OTP: Int = getRandomNumberBetween(10, to: 99)
    

提交回复
热议问题