武警部队装备管理规定:急救~~C语言编程问题

来源:百度文库 编辑:杭州交通信息网 时间:2024/05/01 14:44:41
11-1 下面的程序是用递归算法求整数a的平方根x。求平方根的迭代公式如下:
xn+1 = 0.5*(xn + a/xn)
试问①和②处应该填什么?

#include <stdio.h>
#include <math.h>
double mysqrt(double a, double xn)
{
double x1, y;
xn1 = ① ;
if (fabs(xn1-xn) > 0.00001)
y = mysqrt( ② );
else
y = xn;
return y;
}
void main()
{
double x;
printf("Enter x: ");
scanf("%lf", &x);
printf("The square root of %lf = %lf\n", x, mysqrt(x, 1.0));
}

11-2 编写一个递归函数sum(int n), 求1~n的累加和。并用全局变量和定义在sum函数内的静态局部变量两种方法,打印sum被调用的次数。若在sum函数里用局部变量来统计sum调用次数,会产生怎样的结果。

11-1
(1)(xn+a/xn)/2
(2)a,xn1
11-2
#include "stdio.h"

int s1 = 0;

int sum(int n)
{
static s2 = 0;
s1++;
s2++;

if (n == 1)
{
printf("Static:%d\n", s2);
return 1;
}
else
return sum(n-1) + n;
}

void main()
{
int n;
scanf("%d", &n);
printf("The sum is %d\n", sum(n));
printf("Global:%d\n" ,s1);
}

如果用局部变量,则每次进入sum函数时,该变量都重新初始化,无法起到计数效果。