创建平铺图案
char t1[11][11];
int i=0;
int j=0;
int size = 10;
//Putting "|" for tile1 (0,0) to (11,0)
for(i=0;i<11;i++)
{
while(j=0)
{
t1[i][j] = '|';
}
}
//Putting "-" for tile1 (0,0) to (0,11)
for(j=1;j<10;j++)
{
while(i=0)
{
t1[i][j] = '-';
}
}
//PRINTING "|" for tile1 (0,0) to (11,0)
for(i=0;i<11;i++){
while(j=0){
printf("%c \n",t1[i][j]);
}
printf("\n");
}
//PRINTING "-" for tile1 (0,0) to (0,11)
for(j=1;j<10;j++)
{
while(i=0)
{
printf("%c "), t1[i][j];
}
}所以基本上我希望输出像给定的图像一样。我声明了一个11,11大小的数组,并尝试使用循环来分配数组中的字符。但由于某些原因,它不起作用。
我知道我必须使用循环,所以我在纸上画出了模式,写下了数组的位置,并尝试使用循环赋值。
发布于 2017-11-16 22:33:31
你的程序中有很多错误。让我列出一些:
j = 0将0赋值给j,j == 0比较j是否等于0.while循环中的i或j。printf("%c \n", t1[i][j]);.printf("%c "), t1[i][j];中消除<代码>D15不打印t1[i][j]。但printf("%c ", t1[i][j]);可以。@字符。让我们重写你的代码:
初始化数组:
char t1[11][11];现在,在一个循环中,根据模式为这个11 x 11数组中的每个元素分配一个字符。
for (int i = 0; i < 11; i++){
for (int j = 0; j < 11; j++){
// If its first or last column, then place a | at t1[i][j]
if (j == 0 || j == 10){
t1[i][j] = '|';
}
// Else If its the first or last row, then place a - at t1[i][j]
else if (i == 0 || i == 10){
t1[i][j] = '-';
}
// Else if its the second or second to last row/column
// then place @ at t1[i][j]
else if (i == 1 || i == 9 || j == 1 || j == 9){
t1[i][j] = '@';
}
// Else if its the diagonal, then place a @ at t1[i][j]
else if (i == j){
t1[i][j] = '@';
}
// All remaining places would have a space.
else{
t1[i][j] = ' ';
}
}
}在此之后,数组中的每个元素都将被初始化为某个适当的值。现在,打印整个数组。
for (int i = 0; i < 11; i++){
for (int j = 0; j < 11; j++){
printf("%c\t", t1[i][j]);
}
printf("\n");
}请参阅运行live here的代码。
发布于 2017-11-16 22:33:18
当您使用
printf("%c \n", t1[i][j]);您正在从数组中编写一个字符,并在其后面添加一个换行符,这将打破您的模式。
尝试为这个更改打印循环
for (j = 0; j <= 10; ++j)
{
printf("%s\n" ,t1[j]);
}至于写'@‘字符,我会做一个这样的循环
for (i = 1; i < 10; ++i)
{
for (j = 1; j < 10; ++j)
{
if ((j == 1 || i == 1 || j == 9 || i == 9) || j == i)
t1[i][j] = '@';
}
}发布于 2017-11-16 23:28:24
使用更大的2D数组,您可以使代码更短:
#define VSIZE 13
#define HSIZE 25
char t1[VSIZE][HSIZE];
for(int i = 0; i < VSIZE ; ++i) {
for(int j = 1; j < HSIZE - 2; ++j) {
// default value for odd columns:
char c = ' ';
// but change it to something else in an even column:
if(!(j%2)) {
if(i == 0 || i == VSIZE - 1)
c = '-';
if(i == 1 || i == VSIZE - 2 || 2 * i == j)
c = '@';
}
t1[i][j] = c;
}
t1[i][0] = t1[i][HSIZE - 2] = '|';
t1[i][HSIZE - 1] = '\0'; // turn the row to a string closing it with '\0'
printf("%s\n", t1[i]);
}https://stackoverflow.com/questions/47330977
复制相似问题