gpt4 book ai didi

c - 与 c 的数值积分

转载 作者:太空宇宙 更新时间:2023-11-04 03:58:08 24 4
gpt4 key购买 nike

我必须对文本文件中的一组数据点进行数值积分。

我的数据点看起来像

0.5   0.479425539
1 0.841470985
1.5 0.997494987
2 0.909297427
2.5 0.598472144
3 0.141120008
3.5 -0.350783228
4 -0.756802495
4.5 -0.977530118
5 -0.958924275

我的尝试是

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

double trapezoidalRule (double size, double *x, double *y)
{
double sum = 0.0,increment;
int k;
for (k=1; k<size; k++)
{
increment = 0.5 * (x[k]-x[k-1]) * (y[k]+y[k-1]);
sum += increment;
}
return sum;
_getch();
}
int main ( int argc, char * argv[])
{
char* fileName = argc > 1 ? argv[1] : "C:\\Users\\g\\Desktop\\test.txt";
FILE* inputFile = fopen (fileName, "r");
int k;
double size,*x, *y;
double integral;
if ( inputFile ==NULL)
{
fprintf (stderr, "Open failed for %s\n", fileName);
exit(666);
}
fscanf (inputFile, "%d", &size);
printf (" Number of points: %d\n", size);

x = (double *) calloc (size, sizeof(*x));
y = (double *) calloc (size, sizeof(*y));

for (k=0; k< size; k++)
fscanf (inputFile, "%lg%lg" , x+k, y+k);
integral = trapezoidalRule (size, x, y);
printf ("Integral:", "\n", integral);
printf ("\n");
//printf ("check: ","\n", x[size-1], log(x[size-1]) );
_getch();
}

但我没有得到所需的输出...我不知道出了什么问题...它应该计算积分值,但它不是...而且点数也是错误的...它只是取第一个数字,不计算点数...请帮助...

最佳答案

我认为您离解决方案不远了。该公式至少看起来不错。

也许您在代码中犯的最大错误是您在数据中缺少要读取的点数。所以你的代码可能读作“0.5”作为点数。然后,k 上的循环只针对 k=0(然后 k=1>0.5),这可能就是为什么你只有一个点的原因。为了让它工作,我做了以下更改:

  • 在数据文件的开头添加点数。
  • 更改int size的大小类型
  • 打印积分值printf("Integral: %lg\n", integral);

这使它对我有用。

(大编辑,因为它已被重新标记为 C 而不是 C++)

关于c - 与 c 的数值积分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14603874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com