1、背景:
用一个丢骰子的简单案例熟悉了C语言多文件编程该咋写
2、格式
(1)主函数文件main.c
//文件头part1:所有要使用的函数
#include <stdio.h>;
#include <stdlib.h>;
#include <time.h>;
//文件头part2:放所有函数原型的文件
#inlucde "main.h"
//文件头part3:各个要使用的子文件
#include "funciton1.c"
#inlucde "function2.c"
int main(){
function1(); //在function1.c
function2(); //在function2.c
return 0;
}
(2)乘放所有函数原型、全局变量的文件main.h
void function1(void);
void function2(void);
/*
这里有2个知识点或者说优秀编程规范
1、对全局数据使用const,防止暴露数据
2、头文件方案可以偷懒而不使用“一个文件中定义式声明,其他文件使用extern引用式声明”对方案,但是必须加static。不然file1.c和file2.c都包含main.h,那么这2个文件就都有一个相同的定义式声明,大多数编译器不允许这么做
*/
static const int a = 10;
static const double b = 20'
(3) 放各个函数的子文件(示例:function1.c)
void function1(void){
具体函数逻辑
}
3、案例:丢骰子
(1)主函数
#include <stdio.h>
#include <stdlib.h>
#include "main.h"
#include "random.c"
#include "roll.c"
/*
1、要求用户输入骰子数、骰子的面数;输出掷出的结果;
2、随机数的生成种子基于time()生成真随机数
3、支持循环输入
4、能处理以下错误情况:
(1)side小于1
(2)输入类型不匹配
(3)遇到EOF
*/
/*伪算法:
int main(){
输入函数:骰子数(报错处理)、面数(报错处理)
循环(当不报错的时候){
丢骰子函数(骰子数、骰子的面数);
输入函数;
}
}
丢骰子函数(骰子数、骰子的面数){
while(<骰子数){
随机数函数(骰子的面数)
}
数组存储(所有随机数结果);
对数组求和;
输出结果(骰子数、骰子的面数、数组求和结果)
}
随机数函数(骰子的面数){
种子 = (时间函数返回的某个数)
输出结果 = 种子 % 骰子的面数
}
*/
int main(){
int rolls,sides,result;
//输入函数部分
printf("please input the num of rolls you wanna use:");
if(scanf("%d",&rolls) != 1){
printf("you should have input one num.\n");
};
if(rolls < 1){
printf("you should use 1 roll at least\n");
}
printf("How many sides a roll have? ");
if(scanf("%d",&sides) != 1){
printf("you should have input one num.\n");
};
if(sides < 1){
printf("you should use 1 sides at least\n");
}
while(rolls >= 1 && sides >= 1){
printf("you use %d rolls with %d sides, and your result is %d\n",rolls,sides,roll(rolls,sides));
printf("Another??? please input the num of rolls you wanna use:");
if(scanf("%d",&rolls) != 1){
printf("you should have input one num.\n");
};
if(rolls < 1){
printf("you should use 1 roll at least\n");
}
printf("How many sides a roll have? ");
if(scanf("%d",&sides) != 1){
printf("you should have input one num.\n");
};
if(sides < 1){
printf("you should use 1 sides at least\n");
}
}
//-test输入函数
return 0;
}
(2)main.h
//这里存放丢骰子函数的函数声明
//丢骰子函数
int roll(int rolls,int sides);
//随机数函数
int my_random(int sides);
(3)丢骰子函数
int roll(int rolls,int sides){
int result = 0;
int list[rolls];
for(int i = 0; i < rolls;i++){
list[i] = my_random(sides);
}
for(int i = 0 ;i < rolls;i++){
result += list[i];
}
return result;
}
/*
丢骰子函数(骰子数、骰子的面数){
while(<骰子数){
随机数函数(骰子的面数)
}
数组存储(所有随机数结果);
对数组求和;
输出结果(骰子数、骰子的面数、数组求和结果)
}
*/
(4)随机数函数
/*
随机数函数(骰子的面数){
种子 = (时间函数返回的某个数)
输出结果 = 种子 % 骰子的面数
}
*/
int my_random(int sides){
int seed = (unsigned int)time(0);
seed = seed % sides + 1;
return seed;
}