用迭代法求某数a的平方根。已知求平方根的迭代公式为:x n+1 = (xn + a / xn) / 2 要求前后两次求出的差的绝对值小于10-5。 算法如下: ① 设定一个x的初值x0 ; (在如下程序中取x0=a/2, 通过迭代公式求出x1,可以肯定与真正的平方根相比,误差很大。) ② 用上述公式求出x的下一个值 x1 ; ③ 如此继续下去,直到前后两次求出的x值(x n+1和xn)满足以下关系:|x n+1-xn|<10-5 . #include <stdio.h> #include <math.h> int main() { float a; /* 被开方数 */ float x0, x1; /* 分别代表前一项和后一项 */ printf("Input a positive number:\n"); scanf("%f", &a); x0 = a / 2; /* 任取初值 */ x1 = (x0 + a / x0) / 2; while (fabs(x1 - x0) >= 1e-5) { x0 = x1; x1 = (x0 + a / x0) / 2; } printf("The square root of %5.2f is %8.5f\n", a, x1); return 0; } 运行结果: ===================================== Input a positive number: 2↙ The square root of 2.00 is 1.41421 ===================================== ★ 其中初值是任取的(这里取的a/2) , 试将x0初值换为任意数均可得到如上结果。只是迭代的次数有差异。 ★ 另 外,考虑到while与do-while的差别,此程序用while结构,那是否会出现第一次判断条件时就不成立呢,即不会执行循环体。验证如下:设被开 方数a为4,x0 初值为2,则由迭代公式可得x1值为2,x1=x0 值应该为0, 此时应该不会执行循环体,那么结果是否还是正确的呢? 验证如下: #include <stdio.h> #include <math.h> int main() { float a; float x0, x1; printf("Input a positive number:\n"); scanf("%f", &a); x0 = 2; x1 = (x0 + a / x0) / 2; printf("x0=%f x1=%f x1-x0=%f\n", x0, x1, x1-x0); while (fabs(x1 - x0) >= 1e-5) { x0 = x1; x1 = (x0 + a / x0) / 2; printf("x1=%f\n", x1); /* 若条件成立,则会循环输出 */ } printf("The square root of %5.2f is %8.5f\n", a, x1); return 0; } 运行结果: (没有输出循环体中的内容) =============================================== Input a positive number: 4↙ x0=2.000000 x1=2.000000 x1-x0=0.000000 The square root of 4.00 is 2.00000 =============================================== ★ |
|