1多文件编程
针对c语言 实现模块化编程 声明文件.h .c文件对声明文件.h定义 后使用.c文件做验证 例题为求解一元二次方程的模块设计。
.h声明接口函数文件 声明的每个函数 在.c实现文件中定义功能
1.1 .h声明文件
#ifndef yyec_h
#define yyec_h
extern float qiugen0(float a, float b, float c, float x0);
extern void getRoots(float a, float b, float c, float* x1, float* x2);
extern float duichen(float a, float b, float dcz);
extern float zuizhi(float a, float b, float c, float max);
#endif
1.2 .c 功能实现
.h文件对所有接口函数做出声明 其功能实现在.c文件里
#include <stdio.h>
#include <math.h>
#include “yyec.h”//对于定义函数接口的引用 要用""
float qiugen0(float a, float b, float c, float x0) {
//求根 x0 = (-b) / (2 * a); return x0;
}
void getRoots(float a, float b, float c, float* x1, float* x2)
{ *x1 = (-b + sqrt((b * b - 4 * a * c)) / (2 * a)); *x2 = (-b - sqrt((b * b - 4 * a * c)) / (2 * a));}
float duichen(float a, float b, float dcz)
{ dcz = (-b) / (2 * a);
return dcz;}
float zuizhi(float a, float b, float c, float max) //求最值{ max = (((4 * a * c) - (b * b)) / (4 * a)); return max;}
1.3 验证文件
验证.c文件
#include <stdio.h>
#include “yyec.h”
int main()
{
float a, b, c;
float x0 = 0;
float x1 = 0;
float x2 = 0;
float dcz = 0;
float max = 0;
printf(“请依次输入a,b,c 中间空格分开 回车运行\n”);
scanf_s("%f %f %f", &a, &b, &c);
if (b * b - 4 * a * c == 0)
{
printf(“此时方程根为%f\n”, qiugen1(a, b, c, x0)); }
else if (b * b - 4 * a * c > 0)
{
printf("此时方程的根为 %f %f \n ", qiugen1(a, b, c, x1), qiugen2(a, b, c, x2)); } else {
printf(“无解\n”);
}
printf(“对称轴为: %f\n”, duichen(a, b, dcz));
if(a>0)
{ printf(“最小值是%f\n”, zuizhi(a, b, c, max)); }
else
{ printf(“最大值是%f\n”, zuizhi(a, b, c, max));
}
}
可输入值进行测试
编译环境为vs2019