c语言头文件怎么写~!!最好举个例子!!非常感谢!!

c语言头文件怎么写~!!最好举个例子!!非常感谢!!,第1张

简单办法,先写完整程序,再把一部分抽出去,抽出去的存到 自己的头文件里,在抽出的地方写 #include ...

例如,完整程序(计算平均值):

#include<stdio.h>

double mean(double *y, int N){

int i

double s=0.0

for (i=0i<Ni++) s=s+y[i]

s = s / (double) N

return s

}

void main()

{

double x[10]={1,2,3,4,5,6,7,8,9,10}

printf("mean = %lf\n", mean(x,10))

}

----------------------------------------------

抽出部分 存入 a_x.h :

double mean(double *y, int N){

int i

double s=0.0

for (i=0i<Ni++) s=s+y[i]

s = s / (double) N

return s

}

--------------------------------

程序变:

#include<stdio.h>

#include "a_x.h"

void main()

{

double x[10]={1,2,3,4,5,6,7,8,9,10}

printf("mean = %lf\n", mean(x,10))

}

=============================================

你要是愿意随便抽一块也可以,例如抽出(也叫 a_x.h):

double mean(double *y, int N){

int i

double s=0.0

for (i=0i<Ni++) s=s+y[i]

s = s / (double) N

return s

}

void main()

{

------------------------

程序变:

#include<stdio.h>

#include "a_x.h"

double x[10]={1,2,3,4,5,6,7,8,9,10}

printf("mean = %lf\n", mean(x,10))

}

==============================

语法上,功能上,两种抽法都可以。但第一种方法较好--程序可读性好,不易出错。

一般情况下,头文件里放 函数原型,全局量声明 和 函数定义。

就和写源程序一样,只不过把main(){}中间的东西省了。

只留下结构体、联合体、函数等等就行了。

要用的时候,用#include "头文件名"就可以了。

举个例子吧,如果我们要写一个头文件ps.h:

struct ss{

int a

}p

那么我们在程序中 *** 作:

#include <stdio.h>

#include "ps.h"

int main()

{

p.a = 20/*可以直接调用(头文件中已经声明)*/

printf ("%d", p.a)

return 0

}

就可以了。

我们再来一个排序的头文件sort.h,里面包含一个函数sort()

void sort (int a[], int size){

int i,j,temp

for (i=0i<size-1i++)

for (j=i+1j<sizej++)

if (a[i]>a[j]){

temp = a[i]

a[i] = a[j]

a[j] = temp

}

}

那么在主程序中:

#include <stdio.h>

#include "sort.h"

int main()

{

int i

int array[5] = {5, 3, 4, 2, 1}

/*这里可以直接调用sort!*/

sort(array, 5)

for (i=0i<5i++)

printf ("%d ", array[i]) /*输出已经排序好的数组*/

return 0

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/11573749.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-17
下一篇 2023-05-17

发表评论

登录后才能评论

评论列表(0条)

保存