linux下的c语言-day5

来源:互联网 发布:淘宝开店描述怎么写 编辑:程序博客网 时间:2024/06/05 03:58

这次来谈谈数组,数组是一组固定的,类型相同的元素,使用数组名和一个后多个索引值,就可以访问数组中的任意元素。数组的索引值是从0开始的整数值,每一维数组都有一个索引。


将数组和循环合并使用,提供了一种非常强大的编程技术。熟用数组可以在循环中处理类型相同的大量数据值,无论有多少数据值,操作所需的代码量都不多。还可以用多维数组组织数据。建立这样的数组,每一维数组都用某个特性来选择一组元素,例如与某个时间和地点有关的数据。给多维数据应用嵌套的括号,可以用非常少的代码处理所有的数组元素。


这里编写了一个三子棋的简单游戏,比较滑稽。原理也很简单,只需要用循环的思想,条件的逻辑一步一步来就好了,以下是所有的代码:

#includeint main(){int player = 0;//player number 1 or 2int winner = 0;//the winner playerint i = 0;int choice = 0;//square selection number for turnint row = 0;//row index for a squareint column = 0;//column index for a squareint line = 0;//row or column index in checking loopchar 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 boardprintf("\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 selectiondo{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 squarecolumn = 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 firstif((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;elsefor(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 boardprintf("\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 messageif(winner == 0)printf("\n How boring,it is a draw\n");elseprintf("\n Congratulations!!!,player %d,You are the winner!!!\n",winner);return 0;}

当然,五子棋更加好玩一些


但是起码也有些乐趣把~

这里的do while起了至关重要的作用,为了得到行数和列数,运用运算符--choice很精明的实现了。这是一段相当不错的代码~


下一站,字符串和文本的应用~

0 0
原创粉丝点击