【C++计算π值】

C++计算π值


没有AC!只提供一种思路

问题

圆周率。利用下图公式计算π值(当前、后两次计算出的π值差的绝对值小于规定精确度后,程序输出得到的π值。):此公式错误!
此公式错误!
公式参考链接:http://www.cppfans.com/articles/basecalc/c_pi_10000.asp

编程要求:
①在提示accuracy:后用户输入精确度(输入时只可用指数形式,并且使用小写e),程序给出计算的结果pi(保留4位小数)与当时计算公式中的n值;
②程序输出运算结果后,继续提示accuracy:等待用户输入,并再次输出相应结果,直到用户输入的数小于等于0为止;
③当用户在accuracy:后输入的数小于等于0时,程序输出Bye!结束。注意:程序中涉及到浮点数时要使用double型。

代码

#include <iomanip>
#include <vector>
#include <algorithm>
#include <iostream>

#define ISINT(A) (long double(int(A)) == A)

using namespace std;

long double fun_pi(long double n) {
    long double d = 1.0;
    while (n >= 1.0) {
        d *= (n + 1.0) * (n + 1.0) / (n * (n + 2.0));
        n -= 2;
    }
    return d;
    
// 此递归运算数据量较大,会导致栈溢出
//    if (n == 1.0)
//        return (2.0 * 2.0) / (1.0 * 3.0);
//    else
//        return (n + 1.0) * (n + 1.0) / (n * (n + 2.0)) * fun_pi(n - 2.0);

}

long double fun_le(int accuracy) {
//    long double d = 1.0;
//    while (accuracy != 1) {
//        accuracy--;
//        d *= 0.1;
//    }
//    return d * 0.1;

//此递归数据量小,可以正常使用
    if (accuracy == 1)
        return 0.1;
    else
        return 0.1 * fun_le(accuracy - 1);
}

void fun(int accuracy) {

    long double acc = fun_le(accuracy);
    long double pre_pi, now_pi, next_pi;
    long double max_, min_;
    int count =0;
    for (int i = 1;; i += 2) {
        count ++;
        pre_pi = fun_pi(i - 2) * 2;
        now_pi = fun_pi(i) * 2;
        next_pi = fun_pi(i + 2) * 2;

        max_ = max(next_pi, now_pi);
        min_ = min(next_pi, now_pi);
        if (max_ - min_ < acc) {
            cout << "pi=" << fixed << setprecision(4) << now_pi << "," << "n=" << i + 2 << endl;
            break;
        }
    }
}


int main() {
    while (true) {
        cout << "accuracy:";
        string str;
        cin >> str;
        int accuracy = atoi(str.erase(0, 3).c_str());

        if (accuracy > 0) {
            fun(accuracy);
        } else {
            cout << "Bye!" << endl;
            break;
        }
    }

    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值