[英]how to write a 2D array in a table with c language
我有一個像這樣的項目:它是一個游戲,在隨機生成的方桌中,兩個玩家之間進行游戲,游戲桌數從4到10。玩家擲3個骰子。 第一個骰子和第二個骰子用於位置,第三個骰子是將放入“-”和“ *”組成的表中的值。 桌子看起來像棋盤。 現在我想將此隨機創建的數字插入表中。 我不知道 換句話說,如何將數組插入之前創建的表中? 如您在下面看到的代碼所示,由於這是與朋友共享的項目,我沒有准備好表格,但我會盡快將其發布。 該函數應該找到隨機化的位置和值。 數組的大小在另一個函數中也是隨機的。 一團糟 。
#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("|");
}
}
}
}
這是您要查看的代碼。
#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");
}
}
因此,您可以看到將2D數組打印為表格,也可以將該數組作為參數傳遞給函數printTable()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.