c++ - 尝试添加数组元素给出零

标签 c++ numerical-integration turbo-c++

<分区>

因此,我一直在尝试实现一个小程序,使用过时的 Turbo C++ 编译器(是的,我们仍在使用它!)使用辛普森 1/3 规则计算二重积分,但遗憾的是我似乎受到了打击扼杀故障。每当我尝试在以下给我一个零的程序中添加数组 ax[i] 的元素时。这些元素本身似乎完美地显示出来,但由于某些奇怪的原因,添加它们会导致零。这是一段代码。

#include<iostream.h>
#include<conio.h>
#include<math.h>

double f(double, double);

void main()
{
    clrscr();
    double a, b, c, d, h, k, ans, z[10][10], ax[10];
    int i, j, nx, ny;
    clrscr();
    a=0.0; b=1.0; c=0.0; d=1.8; h=0.25; k=0.30;
    nx = (b-a)/h;
    ny = (d-c)/k;

    for(i=0; i<10; i++)
    {
        for(j=0; j<10;j++)
            z[i][j] = 0;
        ax[i] = 0;
    }

    //Generating the table
    for(i=0; i<=nx; i++)
    {
        for(j=0; j<=ny; j++)
        {
            z[i][j] = f(a+i*h, c+j*k);
        }
    }

    for(i=0; i<=nx; i++)
    {
        ax[i] = 0.0;

        for(j=0; j<=ny; j++)
        {
            if(j==0 || j==ny)
                ax[i] += z[i][j];
            else if(j%2==1)
                ax[i] += 4*z[i][j];
            else
                ax[i] += 2*z[i][j];
        }
        ax[i] *= k/3.0;
        cout<<ax[i]<<endl;
    }

    ans=  1.0;
    //for(int q=0; q<=nx; q++)
        ans= (ax[0])+(ax[1])+(ax[2]);


    cout<<"Value of integral is: "<<ans;
    getch();
}

double f(double x, double y)
{
    float r;
    r = 2*x*y/sqrt(x*x+y*y);
    return r;
}

想法?

最佳答案

double f(double x, double y)
{
    float r;
    r = 2 * x*y / sqrt(x*x + y*y);
    return r;
}

x=0y=0 时除以零,所以 ax[0] 等于 nan .当您将数字相加时,您将得到 nan 作为输出。您需要使用 L'Hopital 规则来评估该限制,并以不同方式处理第一个元素。

关于c++ - 尝试添加数组元素给出零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50204131/

相关文章:

python - python中闭环曲线内的面积

r - 在 R 中评估非常大的阶乘

c++ - 基于 std::is_convertible 的 std::enable_if 未正确推导模板

c++ - 具有独立模块约束的编译时插件/自动工厂注册

matlab - 使用 trapz 求曲线下面积

c++ - Borland C++ v3 for DOS 现在可以在任何地方使用吗?

c++ - 在找到总计并将其插入C++文件中的同时获取垃圾值

c - 长整数问题

c++ - 为什么编译器声称此类方法没有返回值?

c++ - 从 linux 应用程序检测来自 ssh/console 的身份验证尝试