第一种:浮点二分法
#include <iostream>
#include <cmath>
double sqrt_binary_search(double x, double precision = 1e-6) {
if (x < 0) {
std::cerr << "Error: Negative input" << std::endl;
return -1;
}
if (x == 0 || x == 1) {
return x;
}
double left = 0, right = x;
double mid = (left + right) / 2;
while (fabs(mid * mid - x) > precision) {
if (mid * mid < x) {
left = mid;
} else {
right = mid;
}
mid = (left + right) / 2;
}
return mid;
}
int main() {
double x;
std::cout << "请输入一个非负数: ";
std::cin >> x;
double result = sqrt_binary_search(x);
std::cout << "根号(" << x << ")的近似值为: " << result << std::endl;
return 0;
}
//作者太懒了,没有写注释
第二种:逐步逼近法
#include <iostream>
#include <cmath>
double sqrt_approximation(double x, double precision = 1e-6) {
if (x < 0) {
std::cerr << "Error: Negative input" << std::endl;
return -1;
}
if (x == 0 || x == 1) {
return x;
}
double guess = x / 2.0; // 初始猜测值
while (fabs(guess * guess - x) > precision) {
guess = (guess + x / guess) / 2.0; // 逐步逼近法更新猜测值
}
return guess;
}
int main() {
double x;
std::cout << "请输入一个非负数: ";
std::cin >> x;
double result = sqrt_approximation(x);
std::cout << "根号(" << x << ")的近似值为: " << result << std::endl;
return 0;
}
第三种:牛顿迭代法
#include <iostream>
#include <cmath>
double sqrt_newton(double x, double precision = 1e-6) {
if (x < 0) {
std::cerr << "Error: Negative input" << std::endl;
return -1;
}
if (x == 0 || x == 1) {
return x;
}
double guess = x / 2.0; // 初始猜测值
while (fabs(guess * guess - x) > precision) {
guess = (guess + x / guess) / 2.0; // 牛顿迭代法更新猜测值
}
return guess;
}
int main() {
double x;
std::cout << "请输入一个非负数: ";
std::cin >> x;
double result = sqrt_newton(x);
std::cout << "根号(" << x << ")的近似值为: " << result << std::endl;
return 0;
}
~你就只知道复制粘贴嘛,给个赞呗~😘😍