ITAT比赛上的一道C语言算法题

来源:互联网 发布:数据通信协议有哪些 编辑:程序博客网 时间:2024/06/05 07:13

题目:现有21根火柴,两人轮流取,每人每次可取走1- 4根,不可多取,也不能不取,谁取最后一根火柴则谁输。请编写一个程序进行人机对弈,要求人先取,计算机后取;计算机一方为“常胜将军”。

分析:要求计算机为随机取数,并且为“常胜将军”,那么最后一次是人取(取一根),而计算机最后一次取不是随机取到的,是根据人的倒数第二次取值得来的。定义两个变量来控制人机取值。可以用多线程来分别控制人与机。

 代码如下:

 #include<stdio.h>
#include<stdlib.h>
int main()
{
 int sum=0,p1=0,c1=0;
 sum=p1+c1;
 while(sum<=20)
{
  printf("person input a date,but the date is between 1 and 4./n");
  scanf("%d",&p1);
  if(p1<1||p1>4)
  {
   printf("please input a date again!the date of you inputed is wrang!");
   scanf("%d",&p1);
  }
   sum=sum+p1;
   if(sum>=16&&sum<20)
   {
     c1=20-sum;
    printf("the computer have been  inputed a date is %d/n",c1);
           break;
   }
   else
   {
     srand ((int) time (0));
     c1=1+time(NULL)%4;
    printf("the computer have been  inputed a date is %d/n",c1);
   }
    sum=sum+c1;
 
}
 printf("the person is failure!");
 return 0;
}