題目:現有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;
}