Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 梯形规则问题_C_Math_Equation - Fatal编程技术网

C 梯形规则问题

C 梯形规则问题,c,math,equation,C,Math,Equation,如果你构建并运行代码,你会发现它不能正常工作。这是一本书(C语言中的问题解决和程序设计)中的问题。它给出了2个方程,并希望找到曲线下的近似面积。并且添加了n值为2、4、8、16、32、64、128的调用陷阱 我的代码的输出是负数和-nan。 方程式为: g(x) = x^2sinx (a = 0, b = 3.14159) h(x) = sqrt(4-pow(x.2)) ( a =-2, b=2); 代码是: #include <stdio.h> #include <math

如果你构建并运行代码,你会发现它不能正常工作。这是一本书(C语言中的问题解决和程序设计)中的问题。它给出了2个方程,并希望找到曲线下的近似面积。并且添加了n值为2、4、8、16、32、64、128的调用陷阱

我的代码的输出是负数和-nan。 方程式为:

g(x) = x^2sinx (a = 0, b = 3.14159)
h(x) = sqrt(4-pow(x.2)) ( a =-2, b=2);
代码是:

#include <stdio.h>
#include <math.h>
void trap(double a,double b, int n, double *areag, double *areah);
double g(double x);
double h(double x);   
int main(void)
{
    double  areag = 0.0, areah = 0.0;
    double a1 = 0, b1 = 10;
    int n;
    for(n=2;n<=128;n*=2){
        trap(a1, b1, n, &areag, &areah);
        printf("%f %f\n", areag, areah);
    }
    return(0);
}

double g(double x){
    return(pow(x,2)*sin(x));
}
double h(double x){
    return(sqrt(4-pow(x,2)));
}
void trap(double a,double b, int n, double *areag, double *areah){
    int i, l;
    *areag = (b-a)/2*n * ( g(a) + g(b));
    for(i = 1; i<=n-1;i++)
        *areag += 2*g(i);
    *areah = (b-a)/2*n * ( h(a) + h(b));    
    for(l=1;l<=n-1;l++)
        *areah += 2*h(i);
}
#包括
#包括
空洞陷阱(双a,双b,整数n,双*区域G,双*区域H);
双g(双x);
双h(双x);
内部主(空)
{
双面积G=0.0,面积H=0.0;
双a1=0,b1=10;
int n;

对于(n=2;n我不确定打算做什么,因为您没有解释它应该如何工作,但这部分是取负数的平方根:

sqrt(4-pow(x,2))
啊,现在我明白了,这就是你想要集成的函数。问题是你需要将集成范围划分为小块,而不是在更大范围内集成。试试看

*areah += 2*h( (double) i / n);

你不应该在
a+(i/n)*(b-a)
处计算
g
h
,其中
i=0,…,n
,即
a
b
之间的等距点吗?我想,我的算法实现有一些问题。因为输出不正确……谢谢你,还有*areah+=2*h((双精度)l/n);将更改i-->l