c - 辛普森法则积分

标签 c

我的作业之一是创建一个使用辛普森 1/3 规则求和的 C 程序。我遇到了无法解决的问题。有更多经验的人可以给我指出正确的方向吗?

理论上,我的代码集成了 y=ax^2+bx+c,其中用户选择 a、b、c 的值,然后用户选择上限和下限 [d,e]。然后用户选择将区域分割成更多矩形的 n 值(我们将在类里面使用的值是 100,因此该区域被分割成 100 个矩形)。之后它会运行辛普森规则并打印出总和。

//n is required number of iterations.

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

double integral (int a,int b,int c,int d,int e,int n)

int main()
{
    double a, b, c, d, e, n;

    printf("Please select values for y=ax^2+bx+c");
    printf("Please select value for a");
    scanf("%d", &a);
    printf("Please select value for b");
    scanf("%d", &b);
    printf("Please select value for c");
    scanf("%d", &c);
    printf("Please select value for the upper limit");
    scanf("%d", &d);
    printf("Please select value for the lower limit");
    scanf("%d", &e);
    printf("Please select the number of rectangles for the Simpson's Rule (Input 100)");
    scanf("%n", &n);

    int i;  
    double sum=0,length=(double)(d-e)/(n),ad,bd,cd,dd;

    ad=(double)a;
    bd=(double)b;
    cd=(double)c;
    dd=(double)d;
    for (i=0;i<n;i++)
    {
        sum+=(ad*(dd*dd+2*dd*length*i+length*length*i*i)+bd*(dd+length*i)+cd)*length;
        printf("the value is = %d",sum);
    }
    return sum;
}

最佳答案

你为什么这么认为

scanf("%e", &e);

应该是这样吗?

scanf()函数采用格式说明符来匹配扫描的输入,在您的情况下,您希望将值存储在 double 变量中,为此您需要 "%lf" 说明符,因此所有 scanf() 都应更改为

scanf("%lf", &whateverDoubleVariableYouWantToStoreTheResultIn);

您不需要从给定类型的变量转换为相同类型,如下所示

dd=(double)d;

而且,您必须知道 scanf() 返回一个值,您不应该忽略它,因为如果输入错误,您的程序将出现错误,您应该检查 scanf() 在库手册或 C 标准中,以更好地了解如何使用它。

关于c - 辛普森法则积分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29400093/

相关文章:

c - 按字母顺序对结构进行排序

c - 在 C 中使用 audiere 库

c - 指向字符的指针 - 函数中的取消引用

c - `ar` 库覆盖时间戳

c - 无法在 vscode 中调试单个 .c 文件

c - 访问另一个进程中的共享内存缓冲区

带有指针的 c strcat

c - 如何在 C 中使用正则表达式//?单行注释

c - windows:如何停止 irda dongle 定期自动检测

来自 ICC 的 _PGOPTI_Prof_Dump_All() 的 Clang 或 GCC 等价物