本文主要是介绍linux下的c语言-day5,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
这次来谈谈数组,数组是一组固定的,类型相同的元素,使用数组名和一个后多个索引值,就可以访问数组中的任意元素。数组的索引值是从0开始的整数值,每一维数组都有一个索引。
将数组和循环合并使用,提供了一种非常强大的编程技术。熟用数组可以在循环中处理类型相同的大量数据值,无论有多少数据值,操作所需的代码量都不多。还可以用多维数组组织数据。建立这样的数组,每一维数组都用某个特性来选择一组元素,例如与某个时间和地点有关的数据。给多维数据应用嵌套的括号,可以用非常少的代码处理所有的数组元素。
这里编写了一个三子棋的简单游戏,比较滑稽。原理也很简单,只需要用循环的思想,条件的逻辑一步一步来就好了,以下是所有的代码:
#includeint main()
{
int player = 0;//player number 1 or 2
int winner = 0;//the winner player
int i = 0;
int choice = 0;//square selection number for turn
int row = 0;//row index for a square
int column = 0;//column index for a square
int line = 0;//row or column index in checking loop
char board[3][3] = { //the board
{'1', '2', '3'}, //initial values are reference numbers used to select a vacant square for a turn
{'4', '5', '6'},
{'7', '8', '9'}
};
for(i = 0; i < 9 && winner == 0; i++) //the main game loop.the game continues for up to 9 turns as long as there is no winner
{
//display the board
printf("\n\n");
printf(" %c | %c | %c\n", board[0][0],board[0][1], board[0][2]);
printf("---+---+---\n");
printf(" %c | %c | %c\n", board[1][0],board[1][1], board[1][2]);
printf("---+---+---\n");
printf(" %c | %c | %c\n", board[2][0],board[2][1], board[2][2]);
player = i % 2 + 1;
//get valid player square selection
do
{
printf("\n Player %d,please enter the number of the square"
"where you want to place your %c\n",player,(player == 1) ? 'X' : 'O');
scanf("%d", &choice);
row = --choice / 3; //get row index of square
column = choice % 3; //get column index of square
}while(choice < 0 || choice >9|| board[row][column] > '9');
board[row][column] = (player == 1) ? 'X' : 'O'; //insert player symbol
// check for a winning line - diagonals first
if((board[0][0] == board[1][1] && board[0][0] == board[2][2]) || (board[0][2]) == board[1][1] && board[0][2] == board[2][0])
winner = player;
else
for(line = 0; line <= 2 ;line ++)
if((board[line][0] == board[line][1] &&
board[line][0] == board[line][2] ||
board[0][line] == board[1][line] &&
board[0][line] == board[2][line]))
winner =player;
}
//game is over so display the final board
printf("\n\n");
printf(" %c | %c | %c\n", board[0][0],board[0][1], board[0][2]);
printf("---+---+---\n");
printf(" %c | %c | %c\n", board[1][0],board[1][1], board[1][2]);
printf("---+---+---\n");
printf(" %c | %c | %c\n", board[2][0],board[2][1], board[2][2]);
//display result message
if(winner == 0)
printf("\n How boring,it is a draw\n");
else
printf("\n Congratulations!!!,player %d,You are the winner!!!\n",winner);
return 0;
}
但是起码也有些乐趣把~
这里的do while起了至关重要的作用,为了得到行数和列数,运用运算符--choice很精明的实现了。这是一段相当不错的代码~
下一站,字符串和文本的应用~
这篇关于linux下的c语言-day5的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!