利用迭代法求正数的平方根。x0=a/2; pingy.jpg 输入格式: 要求,在一行输入实数a(a>0)和eps(eps>0)。 输出格式: 输出平方根,保留4位小数及迭代次数。
时间: 2024-06-01 12:12:16 浏览: 14
#include <stdio.h>
#include <math.h>
int main() {
double a, eps, x0, x1;
int cnt = 0;
scanf("%lf %lf", &a, &eps);
x0 = a / 2;
x1 = (x0 + a / x0) / 2;
while (fabs(x1 - x0) >= eps) {
x0 = x1;
x1 = (x0 + a / x0) / 2;
cnt++;
}
printf("%.4lf %d", x1, cnt);
return 0;
}
相关问题
用迭代法求某个数的平方根。迭代公式*DE ×0=a/2. (2)迭代结束的判定1x1-x0/<E(给定的精度)
CSDN开发的ChitGPT可以回答您的问题。对于求某个数的平方根,可以使用迭代法。迭代公式为x[i+1]=(x[i]+a/x[i])/2,其中a为待求平方根的数,x[i]为第i次迭代的结果,x[i+1]为下一次迭代的结果。迭代结束的条件是当x[i+1]与x[i]之差的绝对值小于给定的精度E时,认为已经足够接近平方根的值,迭代可以结束。
java根据迭代公式x2=(x1+a/x1)/2,求从键盘输入任意正数a的平方根代码
以下是 Java 代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double a = scanner.nextDouble();
double x1 = a;
double x2 = (x1 + a / x1) / 2;
while (Math.abs(x2 - x1) > 1e-6) {
x1 = x2;
x2 = (x1 + a / x1) / 2;
}
System.out.println(x2);
}
}
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)