c语言程序设计,设计一个函数
写两个函数findRoot和fun,其中fun用来计算f(x) = x4 + 2x3 + x2 – 5 的函数值,而findRoot则利用二分法求方程f(x) = 0在区间(0,2)内的单根,要求精确到小数点后六位,并输出迭代的次数。
要求:
1) 在主函数中输入精度要求和区间端点,将其作为实参传递给findRoot并调用findRoot函数求出方程的根,最后在主函数中输出根。
2) 要求fun函数只能被findRoot函数调用。
思考题:上述findRoot函数是在main()前还是在main()中声明的?fun函数应在哪里声明?在不同位置声明时,可被哪些函数调用?
程序参考
#include <stdio.h>
#include <math.h>
int fun()
{
double findRoot(double a,double b,double d,int *ct);
double y;
int ct;
y=findRoot(0,2,1e-6,&ct);
printf("解为%.6lf
迭代的次数=%d
",y,ct);
}
int main()
{
fun();
return 0;
}
double findRoot(double a,double b,double d,int *ct)
{
double x,f;
*ct=0;
while(1)
{
(*ct)++;
x=(a+b)/2;
f=x*x*x*x+2*x*x*x +x*x - 5;
if (fabs(f)<d)
break;
if (f>0)
b=x;
else
a=x;
}
return x;
}
因为C函数只能返回一个值,所以迭代的次数只能由指针参数返回或定义全局的