在条件中生成随机数

-1 c

我试图在三个条件下生成三个随机数,并且这三个数字必须是从 0 到 100:

  1. 一个奇数
  2. 偶数
  3. 大于 50 的数字

这是我的代码:

#include <stdio.h>
#include <time.h>

int main (void) {
    int num1 = 0, num2 = 0, num3 = 0;

    srand(time(NULL));

    num1 = rand() % 100;
    while (num1 % 2 != 0) {
        num1 = rand() % 100;
    }
    num2 = rand() % 100;
    while (num2 % 2 == 0) {
        num2 = rand() % 100;
    }
    num3 = rand() % 100;
    while (num3 > 50) {
        num3 = rand() % 100;
    }
    printf("your numbers\n%d\n%d\n%d\n", num1, num2, num3);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译器回答我:

警告:函数“srand”的隐式声明 [-Wimplicit-function-declaration]
  srand(时间(空));

而且我确实符合学校的要求:

  • 它必须在循环中
  • 我不能使用breakTRUE不能FALSE

pax*_*blo 7

您的srand()问题仅仅是因为您没有包含stdlib.h, 声明该调用(以及rand()就此而言)的位置。

无论如何,在丢弃“无效”数字时实际上不需要使用循环,您可以为此使用数学:-) (a)

假设 0 到 100包括:

num1 = rand() % 50 * 2 + 1  // 1, 3, 5, ..., 99
num2 = rand() % 51 * 2      // 0, 2, 4, ..., 100
num3 = rand() % 50 + 51     // 51, 52, ..., 100
Run Code Online (Sandbox Code Playgroud)

对于num1%给出一个值0..49,当加倍和递增时,会给出一个在所需范围内的奇数。第二个类似,但范围略有扩大,因为两端都有偶数。第三只是给出了一些0..49映射到51..10051被添加。

如果范围只有半开(0..99含),也可以获得类似的结果:

num1 = rand() % 50 * 2 + 1  // 1, 3, 5, ..., 99
num2 = rand() % 50 * 2      // 0, 2, 4, ..., 98
num3 = rand() % 49 + 51     // 51, 52, ..., 99
Run Code Online (Sandbox Code Playgroud)

如果出于某种奇怪的原因它必须使用循环(尽管效率低下),那么您使用的条件存在一些问题 - 它们基本上都是错误的。换句话说,您希望(例如)在数字为偶数时运行第一个循环,以便最终生成奇数。

您应该能够使用以下内容。每个块都包括将变量初始化为一个值,该值将强制循环开始,然后循环继续直到找到具有所需属性的值:

int num1 = 0;             // even forces loop entry
while ((num1 % 2) == 0)   // wait for odd
    num1 = rand() % 100;

int num2 = 1;             // odd forces loop entry
while ((num2 % 2) == 1)   // wait for even
    num2 = rand() % 100;

int num3 = 1;             // 50 or less forces loop entry
while (num3 <= 50)        // wait for 51+
    num3 = rand() % 100;
Run Code Online (Sandbox Code Playgroud)

所有这些都将潜在值的范围限制为0..99包含,如果您想包含100,只需将表达式更改为rand() % 101


(a)实际上,我不喜欢教育者设置的这些限制。他们实际上是在教低效的编码方法。这将是更好的,如果它是什么,这是一个很多困难,用一个简单的数学运算做(如确保数既不是111743也没有97)。

我怀疑您可以找到一种数学方法来检测它,但仅使用一系列条件会容易得多。现在我只是在等待有人通过提供检测这四个的数学公式来展示我:-)

  • @loaykher,这不是您的问题中列出的要求,并且无论如何,这是完全没有必要的。将添加一个附录。 (3认同)