示例:掷骰子

作者:追风剑情 发布于:2020-1-18 17:07 分类:C

示例:

diceroll.h


  1. #pragma once
  2. extern int roll_count; //引用式声明
  3. int roll_n_dice(int dice, int sides);


diceroll.c


  1. /* 引入标准头文件用<>,引入本地头文件用"" */
  2. #include "diceroll.h"
  3. #include <stdio.h>
  4. /* 提供库函数rand()的原型 */
  5. #include <stdlib.h>
  6.  
  7. int roll_count = 0; /* 定义式声明,外部链接 */
  8.  
  9. /* 该函数属于该文件私有 */
  10. static int rollem(int sides)
  11. {
  12. int roll;
  13. roll = rand() % sides + 1;
  14. ++roll_count; /* 计算函数调用次数 */
  15. }
  16.  
  17. int roll_n_dice(int dice, int sides)
  18. {
  19. int d;
  20. int total = 0;
  21. if (sides < 2)
  22. {
  23. printf("Need at least 2 sides.\n");
  24. return -2;
  25. }
  26. if (dice < 1)
  27. {
  28. printf("Need at least 1 die.\n");
  29. return -1;
  30. }
  31.  
  32. for (d = 0; d < dice; d++)
  33. total += rollem(sides);
  34.  
  35. return total;
  36. }


Main.c

  1. //Visual Studio中加上这句才可以使用scanf()
  2. //否则只能使用scanf_s()
  3. #define _CRT_SECURE_NO_WARNINGS
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <ctype.h>
  7. //malloc()、free()
  8. #include <stdlib.h>
  9. #include <time.h>
  10. #include "diceroll.h"
  11.  
  12. //argc: 参数个数 argv[]: 参数数组
  13. //int main(int argc, char **argv)
  14. int main(int argc, char *argv[])
  15. {
  16. int dice, roll;
  17. int sides;
  18. int status;
  19. srand((unsigned int) time(0)); /* 随机种子 */
  20. printf("Enter the number of sides per die, 0 to stop.\n");
  21. while (scanf("%d", &sides) == 1 && sides > 0)
  22. {
  23. printf("How many dice?\n");
  24. if ((status = scanf("%d", &dice)) != 1)
  25. {
  26. if (status == EOF)
  27. break; /* 退出循环 */
  28. else
  29. {
  30. printf("You should have entered an integer.");
  31. printf(" Let's begin again.\n");
  32. while (getchar() != '\n')
  33. continue; /* 处理错误的输入 */
  34. printf("How many sides? Enter 0 to stop.\n");
  35. continue;
  36. }
  37. }
  38. roll = roll_n_dice(dice, sides);
  39. printf("You have rolled a %d using %d %d-sided dice.\n",
  40. roll, dice, sides);
  41. printf("How many sides? Enter 0 to stop.\n");
  42. }
  43. printf("The rollem() function was called %d times.\n",
  44. roll_count); /* 使用外部变量 */
  45.  
  46. printf("GOOD FORTUNE TO YOU!\n");
  47.  
  48. system("pause");
  49. return 0;
  50. }

运行测试

111.png

标签: C语言

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号