酒桌上的气氛神器【掷骰子】!!!

骰子确实是活跃酒桌气氛的一大神器,因为它的随机带来的不确定性让我们感到紧张和兴奋。所以我们今天来通过一个程序来重新体会一下掷骰子的乐趣。

程序要求
1、输入骰子的面数和个数
2、输出总点数
3、用户决定是否继续
4、退出后返回掷骰子的次数


解题思路

1、获取骰子的面数和个数,面数不能少2面,个数不能少于1个;
2、返回总点数给用户,需要写一个随机数函数,并且种子跟着时间修改,增强随机性

需要用到的新函数rand()、srand()、time()
rand():通过种子来生成一个指定范围内的随机数,rand() 在调用前会确定一下srand() 是否修改过种子
srand():用来修改随机种子的数值
time():返回一个机器的日历时间

scanf() 会返回接受数据的个数,可以通过这个来判断用户输入个数是否合法


CodeBlocks 编译

diceroll.h

#ifndef DICEROLL_H_INCLUDED
#define DICEROLL_H_INCLUDED

//表示roll_count 是外部变量
extern int roll_count;

int roll_n_dice(int dice, int sides);

#endif // DICEROLL_H_INCLUDED

diceroll.c

/** diceroll.c -- 掷骰子模拟程序 */

//与mandydice.c 一起编译
#include "diceroll.h"
#include <stdio.h>
#include <stdlib.h> //提供rand() 的原型

int roll_count = 0;

static int rollem(int sides){    //函数属于该文件私有
    //sides 用来控制骰子的面数
    int roll;

    roll = rand() % sides + 1;
    ++roll_count;   //记录函数调用的次数

    //返回生成的伪随机数
    return roll;
}

int roll_n_dice(int dice, int sides){
    int d;
    int total = 0;

    //判断数据合法性
    if(sides < 2){
        printf("骰子至少需要两面!\n");
        return -2;  //返回属于该判断的错误值
    }
    if(dice < 1){
        printf("至少需要一个骰子!\n");
        return -1;  //返回属于该判断的错误值
    }

    //骰子的个数控制循环次数
    //计算点数的总和
    for(d = 0; d < dice; d++)
        total += rollem(sides);

    return total;
}

manydice.c

/** 多次掷骰子的模拟程序 */
//与diceroll.c 一起编译

#include <stdio.h>
#include <stdlib.h> //为srand() 提供声明
#include <time.h>   //为time() 提供原型
#include "diceroll.h"   //为roll_n_dice 提供原型,为roll_count 变量提供声明

#define ______START______
#define ______END______

int main(void){
    //声明需要用到的变量
    int dice, roll;
    int sides;
    int status;

    ______START______

    //修改种子的值,跟随时间而变化
    srand((unsigned int) time(0));

    printf("请输入骰子的面数,输入0退出\n");
    //确认scanf() 接收到数字了,并且数字的合法的
    while(scanf("%d", &sides) == 1 && sides > 0){
        printf("需要几个骰子呢?\n");

        if((status = scanf("%d", &dice)) != 1){
            //是否输入错误字符
            if(status == EOF)
                break;
            else{
                printf("输入错误,您应该输入一个整数\n");
                printf("请您再次输入\n");
                while(getchar() != '\n')
                    continue;       //处理错误输入
                printf("请输入骰子的面数,输入0 退出\n");
                continue;           //进行下一轮的循环迭代
            }
        }
        //调用函数生成点数总和
        roll = roll_n_dice(dice, sides);
        //输出数据,并进行下一次判断
        printf("您使用了%d个%d面骰子骰出了%d点\n\n", dice, sides, roll);
        printf("请输入骰子的面数,输入0 退出\n");
    }

    ______END______

    printf("一共掷了%d次骰子\n", roll_count);

    printf("游戏结束,祝您生活愉快!\n");

    return 0;
}


当然我们也可以用今天学到的新函数来做一个抽奖程序 可以偷偷摸摸的弄点小手脚 ,但是听说别人年会上大佬写的抽奖程序要被投影出来公开处刑看看有没有问题。太难顶了。

本月更新进度 10/10

创作不易,你的点赞是我最大的动力!!!
我们下次再见 end~

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章