2017.11.3 关于C语言程序设计现代方法第9章第8题

来源:互联网 发布:我的世界展示框js 编辑:程序博客网 时间:2024/06/06 09:47

原题:

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

我的答案:

 1 2 3 4 5 6 7 8 910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
#include <stdio.h>#include <stdlib.h>#include <stdbool.h>#include <ctype.h>int roll_dice(void);bool play_game(void);int main(void){    char ch = 'y';    srand((unsigned) time(NULL));//配置随机数的种子数。    while (ch == 'y')//循环。    {        if (play_game() == true)//返回bool值为true则胜。        {            printf("You Win!\n");        }        else        {            printf("You Lose!\n");//返回bool值为false则负。        }        printf("Play again?\n");        ch = tolower(getchar());//读取一个字符。        getchar();//读取换行符,避免换行符影响到下次循环时的ch的值。        printf("\n");        if (ch != 'y') break;//如果ch中的字符不为y,结束循环。    }    return 0;}bool play_game(void){    int n,point;    n = roll_dice();    switch (n)    {    case 7 :    case 11:        {            printf("You rolled : %d\n",n);//如果掷骰子掷出7和10,胜。            return true;        }        break;    case 2 :    case 3 :    case 12:        {            printf("You rolled : %d\n",n);//如果掷骰子掷出2,3,12,负。            return false;        }        break;    default :    {        printf("You rolled : %d\n",n);//掷出别的点数则继续。        point = n;//把此时的点数值赋给point表示目标值。conti:        n = roll_dice();//再掷一次。(再获取随机点数)        if ( point == n)        {            printf("You rolled : %d\n",n);//与目标值相等则胜。            return true;        }        else        {            if ( n == 7)            {                printf("You rolled : %d\n",n);//掷出7则负。                return false;            }            else goto conti;//掷出非7且与目标值不相等的值,则继续掷骰子。        }    }    }}int roll_dice(void){    int r1,r2,s;    r1 = rand() % 6 + 1;//第一个骰子的点数。    //因为rand()%6取值范围在[0,5]的整数,    //所以加1。    r2 = rand() % 6 + 1;    s = r1 + r2;//把两个点数相加。    return s;//返回两个骰子点数之和。}


需要注意的一点是:

注意:   

在读取字符时,ch = getchar(),读取一个字符,然后回车键,getchar()会读入一个换行符,当循环继续走回来的时候,ch = '\n',而不会读入其他值,此时会出现错误。

 

解决方法:

在下面加一个getchar();使换行符被下面的getchar()读入。避免影响下一步的输入。



阅读全文
1 0
原创粉丝点击