天天看點

YTU 2421: C語言習題 矩形法求定積分

2421: C語言習題 矩形法求定積分

時間限制: 1 Sec  

記憶體限制: 128 MB

送出: 354  

解決: 234

題目描述

寫一個用矩形法求定積分的通用函數,分别求

(說明: sin,cos,exp已在系統的數學函數庫中,程式開頭要用#include<cmath>)。

輸入

輸入求sin(x) 定積分的下限和上限 

輸入求cos(x) 定積分的下限和上限

輸入求exp(x) 定積分的下限和上限

輸出

求出sin(x)的定積分 

求出cos(x)的定積分 

求出exp(x)的定積分

樣例輸入

0 1
0 1
0 1      

樣例輸出

The integral of sin(x) is :0.48
The integral of cos(x) is :0.83
The integral of exp(x) is :1.76      

提示

主函數已給定如下,送出時不需要包含下述主函數

/* C代碼 */  

 int main()  

 {  

     float integral(float (*p)(float),float a,float b,int n);  

     float a1,b1,a2,b2,a3,b3,c,(*p)(float);  

     float fsin(float);  

     float fcos(float);  

     float fexp(float);  

     int n=20;  

     scanf("%f%f",&a1,&b1);  

     scanf("%f%f",&a2,&b2);  

     scanf("%f%f",&a3,&b3);  

     p=fsin;  

     c=integral(p,a1,b1,n);  

     printf("The integral of sin(x) is :%.2f\n",c);  

     p=fcos;  

     c=integral(p,a2,b2,n);  

     printf("The integral of cos(x) is :%.2f\n",c);  

     p=fexp;  

     c=integral(p,a3,b3,n);  

     printf("The integral of exp(x) is :%.2f\n",c);  

     return 0;  

 }  





 /* C++代碼 */  

 int main()  

 {  

     float integral(float (*p)(float),float a,float b,int n);  

     float a1,b1,a2,b2,a3,b3,c,(*p)(float);  

     float fsin(float);  

     float fcos(float);  

     float fexp(float);  

     int n=20;  

     cin>>a1>>b1;  

     cin>>a2>>b2;  

     cin>>a3>>b3;  

     cout<<setiosflags(ios::fixed);  

     cout<<setprecision(2);  

     p=fsin;  

     c=integral(p,a1,b1,n);  

     cout<<"The integral of sin(x) is :"<<c<<endl;  

     p=fcos;  

     c=integral(p,a2,b2,n);  

     cout<<"The integral of cos(x) is :"<<c<<endl;;  

     p=fexp;  

     c=integral(p,a3,b3,n);  

     cout<<"The integral of exp(x) is :"<<c<<endl;  

     return 0;  

 }      

迷失在幽谷中的鳥兒,獨自飛翔在這偌大的天地間,卻不知自己該飛往何方……

#include <stdio.h>
#include <math.h>
float integral(float (*p)(float),float a,float b,int n)
{
    float s=0.0,i,w;
    w=(b-a)/n;
    for(i=a; i<=b; i+=w)
        s+=p(i+w)*w;
    return s;
}
float fsin(float a)
{
    return sin(a);
}
float fcos(float a)
{
    return cos(a);
}
float fexp(float a)
{
    return exp(a);
}
int main()
{
    float integral(float (*p)(float),float a,float b,int n);
    float a1,b1,a2,b2,a3,b3,c,(*p)(float);
    float fsin(float);
    float fcos(float);
    float fexp(float);
    int n=20;
    scanf("%f%f",&a1,&b1);
    scanf("%f%f",&a2,&b2);
    scanf("%f%f",&a3,&b3);
    p=fsin;
    c=integral(p,a1,b1,n);
    printf("The integral of sin(x) is :%.2f\n",c);
    p=fcos;
    c=integral(p,a2,b2,n);
    printf("The integral of cos(x) is :%.2f\n",c);
    p=fexp;
    c=integral(p,a3,b3,n);
    printf("The integral of exp(x) is :%.2f\n",c);
    return 0;
}