我每次在C中的rand()中都得到相同的值

时间:2020-05-02 01:12:12

标签: c random

在此程序中,我需要获取2个随机数,并且其中一个必须等​​于3。要使它们生成,randomSet函数可在while循环中使用,但问题出在主函数中:循环每次给我相同的2个数字。如何在每次迭代中获得不同的数字?

int randomSet(int temp[])
{
  while (temp[0] != 3 && temp[1] != 3)
         {
            temp[0] =rand()%4;
            temp[1] =rand()%4;
         }
}

主要功能是

int main()
{
    srand(time(0));
    int temp[2];
    int x =0,y =0;
    for (int i = 0; i < 5; i++) {
        randomSet(temp);
    }
    return 0;
}

3 个答案:

答案 0 :(得分:1)

在将import os, sys dir_path = os.path.dirname(os.path.realpath(__file__)) parent_dir_path = os.path.abspath(os.path.join(dir_path, os.pardir)) sys.path.insert(0, parent_dir_path) 传递给temp之前,您没有对其进行初始化,因此其内容不确定,从而导致randomSet()具有未定义的行为

我建议您将while (temp[0] != 3 && temp[1] != 3)改为使用randomSet()循环,以便在开始分析其内容之前填充do..while 1次,例如:

temp

答案 1 :(得分:1)

您可以轻松检测代码并查看发生了什么。正如已经指出的那样,关键的必要更改是,在检查函数中的一个(或两个)是否为3之前,必须在输入函数时确定两个随机值。这可以通过do { … } while (…);循环轻松实现。

尽管有相反的建议,但问题中的循环条件还可以,尽管需要从while循环中进行转换。当两个元素都不为3时,循环继续。一旦一个或另一个为3(或两者均为3,但仅检查第一个元素temp[0]),循环便停止。

例如(文件rand19.c):

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

static void randomSet(int temp[])
{
    do
    {
        temp[0] = rand() % 4;
        temp[1] = rand() % 4;
        printf("--  %d  %d\n", temp[0], temp[1]);
    } while (temp[0] != 3 && temp[1] != 3);
}

int main(void)
{
    srand(time(0));
    int temp[2];
    for (int i = 0; i < 5; i++)
    {
        randomSet(temp);
        printf("%d:  %d  %d\n", i, temp[0], temp[1]);
    }
    return 0;
}

示例运行:

$ rand19
--  2  0
--  1  3
0:  1  3
--  0  3
1:  0  3
--  0  3
2:  0  3
--  2  2
--  0  1
--  3  0
3:  3  0
--  2  0
--  2  0
--  1  0
--  1  0
--  2  3
4:  2  3
$ sleep 60
$ rand19
--  3  3
0:  3  3
--  1  3
1:  1  3
--  1  0
--  3  1
2:  3  1
--  3  2
3:  3  2
--  0  2
--  1  1
--  1  2
--  0  1
--  1  2
--  2  1
--  3  1
4:  3  1
$

答案 2 :(得分:0)

int randomSet(int temp[])
{
  while (1)
         {
            x = rand()%4;
            y = rand()%4;
            if (x < 3 && y < 3) 
            {
               temp[0] = x;
               temp[1] = y;
            }
            else
               break;
         }
}
相关问题