一、函数嵌套调用:C语言不能嵌套定义函数,但可以嵌套调用函数。即在调用一个函数的过程中,又调用另一个函数。
例题:用弦截法求方程f(x)=x^3-5x^2+16x-80=0的根
#include<stdio.h>
#include<math.h>
//定义f函数,以实现f(x)=x^3-5x^2+16x-80
float f(float x)
{
float y;
y = x*(x*(x-7)+16)-80;
return y;
}
// 定义xpoint函数,求出弦与x轴的交点
float xpoint(float x1, float x2)
{
float y;
y = (x1*f(x2) - x2*f(x1)) / (f(x2) - f(x1));
return y;
}
//定义root函数,求近似根
float root(float x1, float x2)
{
float x, y, y1;
y1 = f(x1);
do
{
x = xpoint(x1, x2);
y = f(x);
if ((y*y1) > 0)//f(x)与f(x1)同号
{
y1 = y;
x1 = x;
}
else x2 = x;
} while (fabs(y) >= 0.0001);
return x;
}
int main(int agrc, const char *argv[])
{
float x1, x2, f1, f2, x;
do
{
printf("input x1, x2:\n");
scanf("%f %f",&x1, &x2);
f1 = f(x1);
f2 = f(x2);
} while (f1*f2 >=0);
x = root(x1, x2);
printf("A root of equation is %8.4f\n",x);
return 0;
}
二、函数的递归调用:在调用一个函数的过程中又出现直接或间接地调用该函数本身,称为函数的递归调用。
例题:用递归方法求n!
#include<stdio.h>
int main(int argc, const char *argv[])
{
float factorial(int x);
int n;
float y;
printf("input an interger number:\n");
scanf("%d",&n);
y = factorial(n);
printf("%d! = %f\n",n,y);
return 0;
}
float factorial(int x)
{
float f;
if (x < 0){
printf("n<0,dataerror!");
}
else if ((x == 0) || (x == 1))
{
f = 1;
}
else
{
f = factorial(x - 1)*x;
}
return f;
}
|
|