我必须对文本文件中的一组数据点进行数值积分。
我的数据点看起来像
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();
}
但我没有得到所需的输出......我不知道出了什么问题......它会计算积分值,但它不是......点数也是错误的......它只是取第一个数字,而不是计算点数...请帮助...