#include
#include
#include
#define CALLOC(ARRAY, NUM, TYPE) \
ARRAY = (TYPE*) calloc(NUM, sizeof(TYPE)); \
if (ARRAY == NULL) { \
printf("File: %s, Line: %d: ", __FILE__, __LINE__); \
printf("Allocating memory failed.\n"); \
exit(0); \
}
#define REALLOC(ARRAY, NUM, TYPE) \
ARRAY = (TYPE*) realloc(ARRAY, (NUM)*sizeof(TYPE)); \
if (ARRAY == NULL) { \
printf("File: %s, Line: %d: ", __FILE__, __LINE__); \
printf("Allocating memory failed.\n"); \
exit(0); \
}
int calcsqrt(double* sqrta, int n, double* a)
{
int i;
double xp, xn;
for (i=0; i
do {
xp = xn;
xn = 0.5*(xp + a[i]/xp);
} while (fabs(xn-xp) > 1e-6);
sqrta[i] = xn;
}
return 0;
}
int main()
{
double* a = NULL;
double* sqrta = NULL;
int n = 0;
double tmp;
int i;
printf("Please input a series of positive numbers, 0 to end:\n");
while(1) {
scanf("%lf", &tmp);
if (tmp>0) {
n++;
REALLOC(a, n, double);
a[n-1] = tmp;
} else if (tmp==0) {
break;
} else {
printf("The number must be greater or equal to 0.\n");
}
}
CALLOC(sqrta, n, double);
calcsqrt(sqrta, n, a);
for (i=0; i
return 0;
}
编译、链接、运行程序,输入与输出如下:
:!gcc -Wall iter.c -o iter
:! ./iter
Please input a series of positive numbers, 0 to end:
1
2
3
0
1.000000
1.414214
1.732051
我看你的最佳答案那么复杂!!我写了一个简单的……
#include"stdio.h"
#include"math.h"
int main()
{
int i;
double a,x[1000];
while(scanf("%lf",&a)!=EOF)
{
if(a==0) break;
else
{
x[1]=1;
for(i=1;i<=1000;i++)
{
x[i+1]=0.5*(x[i]+(a/x[i]));
if(fabs(x[i+1]-x[i])<=0.00001)
break;
}
printf("%.6f\n",x[i+1]);
}
}
return 0;
}
递归啊