【问题标题】:Random odd numbers between range with the exception of a single number in C [duplicate]范围之间的随机奇数,C中的单个数字除外
【发布时间】:2017-03-31 20:30:55
【问题描述】:

这是我的代码:

alpha = ((rand() % 12) + 1) * 2 + 1;

我想生成 0-25 之间的随机 奇数 数。但整数 13 除外。我怎样才能解决这个问题?谢谢。

【问题讨论】:

  • 生成并检查,如果为 13,则重新生成。
  • 还包含 25 或者 23 是您想要的最后一个? 0-25 之间的措辞有点奇怪......
  • 实际上 gcd(alpha,26)=1 这就是为什么不应该包含 13 的原因。

标签: c random numbers


【解决方案1】:

生成从 0 到 23 的数字。如果是 13,则将 25 存储在变量中:

alpha = ((rand() % 11) + 1) * 2 + 1;
if (alpha == 13) alpha = 25;

【讨论】:

  • 它工作正常,谢谢。
【解决方案2】:
int universe[] = {1, 3, 5, 7, /* ... omit 13 ... */ 25};
int index = randto(sizeof universe / sizeof *universe);
alpha = universe[index];

其中randto(n) 返回从0n 的随机数。

【讨论】:

    【解决方案3】:

    如果 alpha 为 13,则创建一个简单的循环以重试操作:

      int alpha = 13;
      while (alpha == 13)
        alpha = ((rand() % 12) + 1) * 2 + 1;
    

    【讨论】:

    • (附言。我建议您在其他人注意到之前删除此答案。)
    • 有什么问题?
    • 哦,我错了,使用“!=”而不是“==”。我会解决的,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多