欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C语言学习_函数_习题9.8

程序员文章站 2022-05-12 16:13:44
...

C语言程序设计现代方法_习题9.8

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

#include<stdio.h>
#include<stdbool.h>
#include<time.h>
#include<stdlib.h>

int roll_dice(void);
bool play_game(void);

int main()
{
	int wins,losees;
	bool _bool;
	char yon;//yes or not
	
	srand((unsigned) time(NULL));
	do{
		_bool=play_game();
		if (_bool ==true){
			wins++;
			printf("You win!\n\n");
		}
		else {
			losees++;
			printf("You lose!\n\n");
		}
		printf("Play again?(Y|N)");
		scanf(" %c",&yon);	
	} while (yon=='Y');
	printf("\nWins:%d\tLosees:%d",wins,losees);
}
//这个函数用来返回两个色子的和; 
int roll_dice(void)
{
	int a,b;
	a=rand()%6+1;
	b=rand()%6+1;
	return a+b;
}
 //这个函数返回true or false;同时还输出每次色子的值; 
bool play_game(void)
{
	int a,b;
	a=roll_dice();
	if (a==7 || a==11) {
		printf("You rolled:%d\n",a);
		return true;
	}
	else if (a==2 || a==3 || a==12) {
		printf("You rolled:%d\n",a);
		return false;
	}
	else {
		printf("you rolled:%d\n",a);
		printf("Your point is %d\n",a);
		while (1){
			b=roll_dice();
			if (b==a) {
			printf("You rolled:%d\n",b);
			return true;
			}
			else if (b==7){
			printf("You rolled:%d\n",b);
			return false;
			}
			else printf("You rolled:%d\n",b);
		}	
	}
}

遇到的问题:
1、起初在写roll_dice来获取两个随机数的和时,把种子写在了函数体内;因此在主函数中中两次调用roll_dice生成的值相同。解决方法是把种子写在了主函数中,但是这并不是好的解决方法;
2、有一个神奇的现象,如果我不给losees初值,那么losees的初值竟然是1而不是0;奇了怪!
C语言学习_函数_习题9.8
C语言学习_函数_习题9.8

相关标签: C语言学习