我想得到4个不同的随机数,它们的总数必须是100(rN1 + rN2 + rN3 + rn4 = 100)
Just like this:
NSInteger r1, r2, r3, r4;
r1 = arc4random_uniform(96);
r2 = arc4random_uniform(97-r1);
r3 = arc4random_uniform(98-r1-r2);
r4 = 100-r1-r2-r3;
I think, this is the easiest way to do this:
1. Generate 3 random number between 1 to 100.
2. Calculate the sum
3. and generate 4th number as - Add the difference between calculated sum and 100.
BOOL flag = false;
int r,r1,r2,r3;
while (!flag) {
r = arc4random_uniform(100);
r1 = arc4random_uniform(100);
r2 = arc4random_uniform(100);
r3 = arc4random_uniform(100);
if (r+r1+r2+r3 == 100) {
flag = true;
}
}
NSLog(@"%d %d %d %d",r,r1,r2,r3);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.