如何使用函数中生成的两个随机数作为矩阵坐标?

时间:2019-06-02 05:50:16

标签: c random return

我想出了这个函数来生成两个随机数r和c,以便可以将它们用作矩阵板[r] [c]中的坐标。这有可能吗?

int coordAleatoria()
{
    srand((unsigned int)time(0));
    int r=rand()%9;
    int c=rand()%9;
    while(r==c)
    {
        c=rand()%9;
    }
    printf("%d %d", r, c);
    return r;
    return c;
}

这是一款象棋游戏。 PC应该产生随机移动。该函数确实会生成坐标,但我不确定如何使程序将其视为坐标。

我希望我可以在board [r] [c]中获得r和c作为coordAleatoria()中生成的值。

3 个答案:

答案 0 :(得分:2)

您最多不能返回一次。因此,您可以按照注释中Jabberwocky的建议使用结构组合坐标。如果您仍然觉得比这里困难,那就是实现。

#include<stdio.h>
#include<stdlib.h>//for rand()
#include<time.h>//for time()
struct Pair
{
    int row,col;
};
struct Pair coordAleatoria()
{
    int r=rand()%9;
    int c=rand()%9;
    while(r==c)
    {
        c=rand()%9;
    }
    printf("Inside function: row=%d and col=%d\n",r,c);
    //Create a pair
    struct Pair p;
    //Assign values
    p.row=r,p.col=c;
    //return it
    return p;
}
int main()
{
    srand((unsigned int)time(0));
    //Get the returned value as a Pair
    struct Pair p=coordAleatoria();
    //Collect the row and column values
    int r=p.row;
    int c=p.col;
    //Now you can use them here
    printf("Outside function: row=%d and col=%d\n",r,c);
}

答案 1 :(得分:1)

  • rand()%9生成9个不同的值。使用while(r==c),看起来代码正在寻找9 *(9-1)或72个不同的对。要更快地使用方法,请致电rand()

  • 代码可以返回单个int,然后返回9的神圣代码/ mod,以恢复行/列。

  • srand((unsigned int)time(0));不应在coordAleatoria()中重复调用。只需在main()中调用一次即可。


int coordAleatoria(void) {
  int rc = rand()%72;
  int r = rc/9;
  int c = rc%9;
  if (r==c) r++;
  return (r*9) + c;
}

答案 2 :(得分:0)

您不必调用两次rand()(在通过调用srand()为随机数生成器正确植入种子之后),只需调用一次rand()并将前两位数字作为坐标即可,例如

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

typedef struct {
    int x, y;
} pair_t;

void rand_coords (pair_t *coords)
{
    int n = rand();

    coords->x = n % 10;
    n /= 10;
    coords->y = n % 10;
}

int main (void) {

    pair_t coords = { .x = 0 };

    srand (time (NULL));         /* seed random number generator */

    rand_coords (&coords);

    printf ("coords.x : %d\ncoords.y : %d\n", coords.x, coords.y);

    return 0;
}

取实际坐标范围的模)

使用/输出示例

$ ./bin/coords_rand
coords.x : 9
coords.y : 8

$ ./bin/coords_rand
coords.x : 1
coords.y : 1

$ ./bin/coords_rand
coords.x : 5
coords.y : 7

$ ./bin/coords_rand
coords.x : 8
coords.y : 0