码迷,mamicode.com
首页 > 其他好文 > 详细

搬山游戏

时间:2015-04-03 21:07:16      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:算法   c   

问题;

         设有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.
*/


搬山游戏

标签:算法   c   

原文地址:http://blog.csdn.net/orangeisnotapple/article/details/44859029

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!