#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
char op;
int n = 0, m, flag = 0;
srand(time(NULL));
int x = rand() % 2;
if (x == 0) printf("玩家先报!\n");
else printf("电脑先报!\n");
do
{
if (x == 0 || flag == 1)//玩家报数
{
flag = 1;
printf("请输入你的报数:");
scanf_s("%d%c", &n, &op);
if (op == ' ')//如果你报两个数,比如5 6,则op等于空格,然后再输另一个数
{
scanf_s("%d", &m);
n = m;
}
else (op == '\n');//如果你报一个数,比如7,则op等于回车换行,就不再输入数据了
if (n == 30)
{
printf("你赢了电脑!");
break;
}
}
if (x == 1 || flag == 1)//电脑报数
{
flag = 1;
printf("电脑报数为:");
if ((30 - n) % 3 == 1)
{
printf("%d\n", n + 1);
n = n + 1;
}
else if ((30 - n) % 3 == 2)
{
printf("%d %d\n", n + 1, n + 2);
n = n + 2;
}
else
{
int y = rand() % 2;
if (y == 0)
{
printf("%d\n", n + 1);
n = n + 1;
}
else
{
printf("%d %d\n", n + 1, n + 2);
n = n + 2;
}
}
if (n == 30)
{
printf("你输了!");
break;
}
}
} while (n < 30);
return 0;
}
用函数
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int ramdom();//随机生成0或者1
int computer_input(int n);//电脑报数
int player_input(int n);//玩家报数
int main()
{
int n = 0;
int x = ramdom();
if (x == 0) printf("玩家先报!\n");
else printf("电脑先报!\n");
if (x == 1) n = computer_input(n);
do
{
n = player_input(n);
if (n == 30)
{
printf("你赢了电脑!");
break;
}
n = computer_input(n);
if (n == 30)
{
printf("你输了!");
break;
}
} while (n < 30);
return 0;
}
int ramdom()
{
srand(time(NULL));
return rand() % 2;
}
int computer_input(int n)
{
printf("电脑报数为:");
if ((30 - n) % 3 == 1)
{
printf("%d\n", n + 1);
n = n + 1;
}
else if ((30 - n) % 3 == 2)
{
printf("%d %d\n", n + 1, n + 2);
n = n + 2;
}
else
{
if (ramdom() == 0)
{
printf("%d\n", n + 1);
n = n + 1;
}
else
{
printf("%d %d\n", n + 1, n + 2);
n = n + 2;
}
}
return n;
}
int player_input(int n)
{
char op;
int m;
printf("请输入你的报数:");
scanf_s("%d%c", &n, &op);
if (op == ' ')
{
scanf_s("%d", &m);
n = m;
}
else (op == '\n');
return n;
}