简体   繁体   English

如何用C语言在表中编写2D数组

[英]how to write a 2D array in a table with c language

I have a project which is like this: its a game to between two players in a randomly generated square table from 4 to 10. players roll 3 dices. 我有一个像这样的项目:它是一个游戏,在随机生成的方桌中,两个玩家之间进行游戏,游戏桌数从4到10。玩家掷3个骰子。 the first dice and second are used for the location and the 3rd dice is the value which will be put into a table made of '-' and '*'. 第一个骰子和第二个骰子用于位置,第三个骰子是将放入“-”和“ *”组成的表中的值。 the table looks like a checkers board. 桌子看起来像棋盘。 now i want to insert this number created randomly into the table. 现在我想将此随机创建的数字插入表中。 I don't know how. 我不知道 in other words, how do you insert an array into a table that was made before? 换句话说,如何将数组插入之前创建的表中? as you can see the code is below, since this is a shared project with a friend i don't have the table ready but i'll post it as soon as possible. 如您在下面看到的代码所示,由于这是与朋友共享的项目,我没有准备好表格,但我会尽快将其发布。 this function is supposed to find the randomize the location and the value. 该函数应该找到随机化的位置和值。 also the size of the array is randomized in another function. 数组的大小在另一个函数中也是随机的。 it's a mess . 一团糟 。

#include <stdio.h>
int rolldice(int p)
{
   int x,y,z;
   int ar[p][p];
   x=1+rand%6;
   y=1+rand%6;
   if(z==0){
      z=1+rand%6;
      ar[x][y]=z;
   }
   else {
      printf("other player roll please");
   }
   return z;
}
int table(int n);
int main(){

int size,t;
srand(time (NULL));
size = 4 + ( rand() % 7);
int array[size][size];
table(size);
rolldice(size)
}
int table(int n){
int k,a,m;
int ar[n][n];
for (m=1;m<=n;m++){
printf(" __");
}
for (k=1;k<=n;k++){
    printf("\n");   
    for (a=1;a<=n;a++){
        printf("|__");
        printf("%c",ar[k][a]);
        if(a==n){
            printf("|");
        }
    }
}
}

Here is the code you wanted to see. 这是您要查看的代码。

#include <stdlib.h>

#define SIZE 4

int ar[SIZE][SIZE]=
{
    {1, 0, 3, 8},
    {4, 0, 5, 0},
    {9, 0, 2, 1},
    {1, 0, 6, 2}
};

int main() {
    printTable();

    return 0;
}
printTable(){
    int i;
    int j;

    for(i = 0; i<SIZE+1;i++){
        for(j=0; j<SIZE+1;j++){
            if(i==0 || j==0 || j==SIZE || i==SIZE)
                printf(" * ");
            else if(j==SIZE-1)
                printf("%d",ar[i][j]);
            else
                printf("%d - ",ar[i][j]);
        }
        printf("\n");
    }
}

So as you can see this prints 2D array as a table, its also possible to pass that array as a parameter to function printTable() . 因此,您可以看到将2D数组打印为表格,也可以将该数组作为参数传递给函数printTable()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM