递归函数
函数调用自己称为递归;递归在程序设计中并不常见。递归在某一些情况下,是一个效率很高的技巧;
#include <stdio.h>
unsigned long factorial(unsigned long);
int main(void)
{
unsigned long number = 0L;
printf("\nEnter an inteager value:");
scanf("%lu",&number);
printf("\nThe factorial of %lu is %lu \n",number,factorial(number));
return 0;
}
unsigned long factorial(unsigned long n)
{
if(n < 2L)
return n;
return n*factorial(n - 1);
}
Enter an inteager value:5
The factorial of 5 is 120
Press any key to continue
可变元的函数
在标准库中,某些函数的变元数是可变的,例如函数printf()
和scanf()
。标准库<stdarg.h>
提供了编写这种函数的例程。
编写参数可变的函数时,要使用的3个宏:va_start()、va)_arg、va_end()。
#include <stdio.h>
#include <stdarg.h>
double average(double v1 , double v2,...);
int main(void)
{
double Val1 = 10.5,Val2 = 2.5;
int num1 = 6,num2 = 5;
long num3 = 12,num4 = 20;
printf("\n Average = %lf",average(Val1,3.5,Val2,4.5,0.0));
printf("\n Average = %lf",average(1.0,2.0,0.0));
printf("\n Average = %lf",average((double)num2,Val2,(double)num1,(double)num4,(double)num3,0.0));
printf("\n");
return 0;
}
double average(double v1 , double v2,...)
{
va_list parg;
double sum = v1 + v2;
double value = 0;
int count = 2;
va_start(parg,v2);
while ((value = va_arg(parg,double)) != 0.0 )
{
sum += value;
count++;
}
va_end(parg);
return sum/count;
}
长度可变函数的变元列表的基本规则
- 在变元函数中,至少有一个固定变元;
- 必须调用va_start()初始化函数中可变元列表指针的值;
- 必须有确定每个变元的类型的机制;
- 必须有确定变元终止的机制;
- va_arg()的第二个变元制定了变元的类型;
- 在退出可变元函数时,要调用va_end()释放va_list类型指针;