三种C++进行开平方运算的程序

第一种:浮点二分法

#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;
}

          ~你就只知道复制粘贴嘛,给个赞呗~😘😍

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值