思修课无聊搞出来的东西
题目:
手撸代码
#include <iostream>
#include <cmath>
using namespace std;
double Tn(double a, double b, double n,int sumtype);
double f1(double x);
double f2(double x);
double f3(double x);
const int PI = 3.1415926;
int main()
{
double n, a, b;int sumtype;
cout << "Please enter a b n,sum 1 or 2 or 3" << endl;
cin >> b >> a >> n >> sumtype;
double result = Tn(a, b, n,sumtype);
cout << "result is " << result << endl;
}
double Tn(double a, double b,double n, int sumtype)
{
double h = (b - a) / n;
double (*f)(double);
switch (sumtype)
{
case 1: f = f1; break;
case 2: f = f2; break;
case 3: f = f3; break;
default: abort();
break;
}
double fa = f(a); double fb = f(b); double sum = 0;
for (int i=1; i < n; i++)
{
sum += f(a + i*h);
}
return h * (f(a) + f(b)) / 2 + h * sum;
}
double f1(double x)
{
return 4 / (1 + x * x);
}
double f2(double x)
{
return sqrt(1 + x * x);
}
double f3(double x)
{
return sin(x);
}
注意,22行定义指针时,要带上形参(double),且要用(*p),因为优先级的原因,否则会报错!!!
然后就可以愉快地求积分啦!再也不用担心数学作业不会啦!(逃——)
这个是第三个函数的结果,可以发现,在π精度很高,和切片n很多的时候,得到了正确的积分::one: