如何在C中创建数字网格



我想创建一个从1到30的数字的网格。我可以决定要通过用'x'替换它来解决哪个数字。但是我什至无法在char [] []。

中打印出网格

1 2 3 4 5 6

7 8 9 x 11 12

13 14 15 16 17 18

19 20 21 22 23 24

25 26 27 28 x 30

该程序给了我

123456
678911
111111
111122
222222

我该如何解决?谢谢!

int i, j, x;
char plan[6][5];
for (i=0; i<5; i++)
    for (j=0; j<6; j++)
        {
            x = i*5+j+1;
            sprintf(&plan[i][j], "%d", x);
        }
        
    
for (i=0; i<5; i++)
{
    for (j=0; j<6; j++)
        printf("%c", plan[i][j]);
    printf("n")    ;
}
在从char转换为char*。更好的是您应该使用&plan[i][j] ..但是它将仅存储一个数字,要解决此问题,您可以将网格的每个元素视为字符串。(我认为这不是一种适当的方法,但它将产生所需的所需输出)。
#include <stdio.h>
    int main(){
    int i, j, x;
    char plan[5][6][3];
    for (i=0; i<5; i++)
        for (j=0; j<6; j++)
            {
                x = i*6+j+1;
                sprintf(plan[i][j], "%d", x);
            }

    for (i=0; i<5; i++)
    {
        for (j=0; j<6; j++)
            printf("%s ", plan[i][j]);
        printf("n")    ;
    }
    }

对于手头的问题,您需要获取一个指针,指向要放置值的位置。使用&获取地址:

sprintf(&plan[i][j], "%d", x);

但是,一旦这样做,您将发现一个新问题。您的2D字符阵列只会在每个位置存储一个字符。对于两位数的数字,这将是一个问题。

好的,这花了一段时间:

在您的问题中,代码的第一个大错误是:它应该是plan[5][6],而不是plan[6][5]

而不是使用3D数组并利用更多内存,一个简单的选择是使用数据类型string如下:

#include<iostream>
#include <stdio.h>
using namespace std;
int main(void)
{
int i, j, x;
string plan[5][6];
x=1;//note that i increment this after every j loop is over
for (i=0; i<5; i++){
    for (j=0; j<6; j++) {
            char out[5];
            sprintf(out,"%d",x);
            plan[i][j].assign(out);
            x+=1;//note that i increment this after every j loop is over
        }
}
for (i=0; i<5; i++) {
    for (j=0; j<6; j++)
        printf(" %s ", plan[i][j].c_str());   
    printf("n")    ;
}
}

并且为了按照您的问题所述列出x,您可以简单地做。plan[i][j].assign("x")

最新更新