北京理工大学CPP上机实验0330

Readme

本题目为2022年3月30日上机题
1.求积分的数值解
2.求任意位数的圆周率

第一题

#include <iostream>
#include <math.h>
using namespace std;

//龙贝格法求积分的数值解


double fun(double x)
{
    // return sin(x)+x*cos(x);//原函数
    return sin(x) / x;
}
double romberg(double a, double b, double (*f)(double), double eps)
{ //上下限、被积函数、精度
    double T1, T2, S1, S2, C1, C2, R1, R2, S, x;
    double h = b - a;
    T1 = h / 2 * ((*f)(a) + (*f)(b));
    // cout<<T1;
    int k = 0;
    while (1)
    { // k++;
        S = 0;
        x = a + h / 2;
        do
        {
            S = S + (*f)(x);
            x = x + h;
        } while (x < b);
        // if s>=b
        T2 = T1 / 2 + h / 2 * S;
        // cout<<T2;
        // if(fabs(T2-T1)<eps) return T2;
        S2 = T2 + 1 / 3 * (T2 - T1);
        if (k == 1)
        {
            k++;
            h = h / 2;
            T1 = T2;
            S1 = S2;
            //   cout<<S2;
            continue;
        }
        C2 = S2 + 1 / 15 * (S2 - S1);
        if (k == 2)
        {
            k++;
            h = h / 2;
            T1 = T2;
            S1 = S2;
            C1 = C2;
            continue;
        }
        R2 = C2 + 1 / 63 * (C2 - C1);
        if (k == 3)
        {
            k++;
            h = h / 2;
            T1 = T2;
            S1 = S2;
            C1 = C2;
            R1 = R2;
            continue;
        }
        if (fabs(R2 - R1) < eps)
        {
            cout << k << endl;
            return R2;
        }
        k++;
        h = h / 2;
        T1 = T2;
        S1 = S2;
        C1 = C2;
        R1 = R2;
        continue;
    }
}
int main()
{
    double eps, a, b;
    cout << "请输入积分上下限: " << endl;
    cin >> a >> b;
    cout << "请输入精度:" << endl;
    cin >> eps;
    double ans = romberg(a, b, *fun, eps);
    cout << ans;
    return 0;
}

第二题

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    int Decimal_Digits = 0;    //小数点位数;
    const int Side_Length = 1; // 设定?的半径为1
    double ans = 0;             //初始化m;
    int Side_Number = 9999;    
    const double PI = 3.141592654;
    double Degree = 0;
    double S = 0;
    cout << "您想要计算的总位数:" << endl;
    cin >> Decimal_Digits;
    for (int i = 0; i <= 100; i++, Side_Number++)
    {
        Degree = (360.0 / Side_Number) / 180 * PI;
        S = 0.5 * Side_Length * Side_Length * sin(Degree) * Side_Number;
        ans = S / (Side_Length * Side_Length);
        cout.precision(Decimal_Digits);
        
    }

    cout<< ans << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值