问题;
设有n座山,计算机与人作为比赛双方,轮流搬山,规定每次搬山数不超过k,谁搬最后一座山谁输。
#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int n, k, x, y, cc, pc, g; printf("More Mountain Game\n"); printf("Game begin\n"); pc = cc = 0; g = 1; for( ; ;) { printf("No.%2d game \n", g++); printf("-------------\n"); printf("how many montains are there?"); scanf("%d", &n); if(!n) break; printf("how many montains are allow to each time?"); do { scanf("%d", &k); if(k>n || k<1) printf("Repeat again!\n"); }while(k>n || k<1); do //这是人的搬山方法 { printf("how many montains do you wish move away"); scanf("%d", &x); if(x<1 || x>k || x>n) { printf("IIIegal, again please!\n"); continue; } n -= x; printf("There are %d montains left now.\n", n); if(!n) { printf(".......i win. you are fail.....\n\n"); cc++; } else //这是机器的搬山方法 { y = (n-1)%(k+1);//关键算法 if(!y) y=1; n-=y; printf("Computer move %d montiains away.\n", y); if(n) printf("There are %d mountains left now.\n", n); else { printf("........i am fail. you win\n\n"); pc++; } } }while(n); } printf("total have played %d.\n", cc+pc); printf("you score is win %d, lose %d.\n", pc, cc); printf("you score is win %d, lose %d.\n", cc, pc); return 0; } /* More Mountain Game Game begin No. 1 game ------------- how many montains are there?10 how many montains are allow to each time?3 how many montains do you wish move away3 There are 7 montains left now. Computer move 2 montiains away. There are 5 mountains left now. how many montains do you wish move away2 There are 3 montains left now. Computer move 2 montiains away. There are 1 mountains left now. how many montains do you wish move away1 There are 0 montains left now. .......i win. you are fail..... No. 2 game ------------- how many montains are there?0 total have played 1. you score is win 0, lose 1. you score is win 1, lose 0. */
原文地址:http://blog.csdn.net/orangeisnotapple/article/details/44859029