编写函数模拟掷骰子的游戏(两个骰子)。第一次掷的时候,如果点数之和为7或11则获胜;如果点数之和为2、3或12则落败;其他情况下的点数之和称为“目标”,游戏继续。在后续的投掷中,如果玩家再次掷出“目标

编写函数模拟掷骰子的游戏(两个骰子)。第一次掷的时候,如果点数之和为7或11则获胜;如果点数之和为2、3或12则落败;其他情况下的点数之和称为“目标”,游戏继续。在后续的投掷中,如果玩家再次掷出“目标”点数则获胜,掷出7则落败,其他情况都忽略,游戏继续进行。每局游戏结束时,程序询问用户是否再玩一次,如果用户输入的回答不是y或Y,程序会显示胜败的次数然后终止。
#include"stdio.h"
#include"stdlib.h"
#include"time.h"


int roll_dice()
{
	int n1,n2;

	srand(time(0));

	n1=rand()%6+1;
	n2=rand()%6+1;
	printf("You rolled:%d\n",n1+n2);
	return n1+n2;
}

int lose=0,win=0;

int play_game()
{
	int n,m,flag=1;

	m=roll_dice();
	

	if(m==7 || m==11)
	{
		win++;
	}
		else
		if(m==2 || m==3 || m==12)
		{
			lose++;
		}else
			printf("Your point is %d\n",m);
	

	while(flag)
	{
		n=roll_dice();
		if(n==7)
		{
			printf("You lose!\n");
			lose++;
			flag=0;
		}
			else
				if(n==m
					)
				{
					printf("You win!\n");	
					win++;
					flag=0;
				}
					else
					{
					flag=0;
					printf("You roll :%d\n",n);
					}
	}
	return 0;
}



int main()
{

	char ch='y';
	while(ch=='y' ||ch=='Y')
	{
		play_game();
		printf("Play again?\n");
		
		ch=getchar();
		getchar();
	}
	printf("Wins=%d;Loses=%d\n",win,lose);
	
	return 0;
}

  • 1
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
好的,我可以帮你解答这个问题。下面是用C语言编写掷骰子游戏的代码: ```c #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { int dice1, dice2, sum; int point, count = 1; srand(time(NULL)); // 初始化随机数种子 dice1 = rand() % 6 + 1; dice2 = rand() % 6 + 1; sum = dice1 + dice2; printf("第一次掷骰子点数和为:%d\n", sum); if (sum == 7 || sum == 11) { printf("恭喜,您获胜了!\n"); } else if (sum == 2 || sum == 3 || sum == 12) { printf("很遗憾,您输了!\n"); } else { point = sum; printf("您需要点数是:%d\n", point); while (count <= 7) { dice1 = rand() % 6 + 1; dice2 = rand() % 6 + 1; sum = dice1 + dice2; printf("第%d次掷骰子点数和为:%d\n", count, sum); if (sum == point) { printf("恭喜,您获胜了!\n"); break; } else if (sum == 7) { printf("很遗憾,您输了!\n"); break; } else { count++; } } if (count > 7) { printf("很遗憾,您输了!\n"); } } return 0; } ``` 这个程序首先利用`srand()`函数和`time()`函数初始化了随机数种子,然后用`rand()`函数模拟掷骰子的过程,得到两个随机数作为两个骰子点数,计算它们的和。根据游戏规则,如第一次掷骰子点数和为7或11,则游戏获胜;如为2、3或12,则游戏者输;如为4、5、6、8、9或10,则将这个和作为游戏获胜需要点数继续骰子,直到赚到该点数时算是游戏获胜,或者连续掷骰子7次都没有赚到该点数,则游戏者输。 你可以尝试编译并运行这个程序,测试一下掷骰子游戏的结

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值