7月7日助教题解

解法 一  : 该式为 a 到 b  上 f ( x ) 的积分,考虑先分割,再求和,当分割的区间足够小的时候,分割的小矩形的面积和即为a到b上的积分

不妨设 小区间的长度为0.000001,直接暴力计算面积和即可。

#include<math.h>
#include<stdio.h>
const double eps=1e-6;
double f(double x){
    return x*x/(log(x+1));
}
int main(){
    int a,b;
    while(~scanf("%d %d",&a,&b)){
        double d=0;
        for(double  x=a*1.0;x<=b*1.0;x+=eps){
            d+=f(x)*eps;
        }   
        printf("%.2lf
",d);
    }
    return 0;
}
View Code

解法二 : 辛普森积分

 直接枚举这个近似的式子必然精度不够,考虑自适应辛普森积分公式,递归划分区间求解

#include<math.h>
#include<stdio.h>
const double eps=1e-6;
double f(double x){
    return x*x/log(x+1);
}
double simpson(double a,double b){
    double c=(a+b)/2.0;
    return (f(a)+f(b)+4.0*f(c))*(b-a)/6.0;
}
double ars(double a,double b,double eps){
    double c=(a+b)/2.0;
    double mid=simpson(a,b),l=simpson(a,c),r=simpson(c,b);
    if(fabs(l+r-mid)<=15*eps)
        return l+r+(l+r-mid)/15.0;
    return ars(a,c,eps/2.0)+ars(c,b,eps/2.0);
}
int main(){
    int a,b;
    while(~scanf("%d %d",&a,&b)){
        double s=ars(a,b,eps);
        printf("%.2lf
",s);
    }

    return 0;
}
View Code
原文地址:https://www.cnblogs.com/littlerita/p/13253461.html