1

是否可以生成 1 -10 之间的随机数,但它不应该是 5?

4

3 回答 3

6
#include <stdlib.h>

// ...

int i;

do {
   i = rand() % 10 + 1; // generate random number from 1 to 10
} while (i == 5);       // repeat until number != 5
于 2011-12-02T14:03:10.970 回答
6
int x = arc4random()%9;
x += x>=4? 2 : 1
于 2011-12-02T14:04:40.797 回答
2

一个简单的解决方案是使用系统函数生成 1-10 之间的随机数,如果恰好是 5,则再次生成它,直到不是这种情况。这个解决方案有一个很小的概率,你的函数在 iPhone 电池死之前不会返回:)。下面列出了替代方案

另一种解决方案是使用 1-9 之间的系统函数生成一个随机数,并将 5-9 映射为 6-10

int GenRandomNumber()
{
    int x = GetSystemRandomBetween1and9();
    if ( x >= 5 )
      x += 1;
    return x;
}
于 2011-12-02T14:02:38.410 回答