C program: CHESS program problem

2008-11-22 10:09 pm
I would like to ask,
after I have input the value of the row number and column number of a chess,
what method should I use to put that chess into correct location.

for example, If I input ( r = 5, c = 5)
the chess should be located at ( 5, 5)

that is:
the output should be
________________
1 2 3 4 5 6 7 8 9
1
2
3
4
5 *
6
7
8
9

_________________

but I do not know how to use array to finish the program
Can anyone give some hints?
thank you for your help
圖片參考:http://http.cdnlayer.com/dreamincode/forums/style_emoticons/default/smile.gif


the below is my code
_________________
#include <stdio.h>

int main()
{
int row;
int column;
int r, c;

printf("Please input the row no. & column no. of the stone: ");
scanf("%d %d", &r, &c);

for ( row = 1; row <= 9; row ++ ){
printf(" %d", row);
}
printf("\n");
for ( column = 1; column <= 9; column ++ ){
printf("%d \n", column);
}

if ( r > 9 || c > 9 || r < 1 || c < 1 ){
printf("Wrong number! Input again!\n");
}


return 0;
}

回答 (1)

2008-11-23 8:15 am
✔ 最佳答案
The International chessboard is an 8x8, and the Chinese chess board has 9columns x10rows. I assume you are working with chinese chess, in which case you need to adjust the number of rows.
In general, any chess board can be represented by a two-dimensional array, which you define in C or C++.
If you are writing in C++, you can define two constants for the maximum number of rows and columns, such as:
const int maxrow=10, maxcol=9; // for chinese chess
int board[maxrow][maxcol];
If you are writing in C, I am not sure if you can use the const keyword, so you would write
int maxrow=10, maxcol=9;
but you may have to stick with
int board[10][9]; // for chinese chess
After that, you would initialize it to 0 to mean that it is empty, for example
int i,j;
for(i=0;i<maxrow;i++)for(j=0;j<maxcol;j++)board[i][j]=0;
After you have entered the coordinates of the piece, you would set it to 1 (for red) or 2 (for green).
scanf(...., &r, &c);
board[r][c]=1;
print(board, r,c)
You can then print the board with a method print such as:
void print(int board[], int maxrow, int maxcol)
{
int i,j'
char piece[2]={' ','1','2'};
for(i=maxrow-1;i>=0;i--)// print top row first
{
printf("%2d",i); // print row number
for(j=0;j<maxcol;j++)printf(" %c",piece[board[i][j]]); // print whole row
printf("\n");//new line
}


收錄日期: 2021-04-13 16:15:43
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20081122000051KK00965

檢視 Wayback Machine 備份