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