当我在文档中输入值并从同一个循环中打印出来时,我会打印出正确的值。但是,只要我将这些值放在另一个循环中的数组之后大约一半我得到了错误的值,其他人都同意。谢谢你的帮助!
int main( ){
int i = 0;
int n = 0;
float x, y, x1, y2;
FILE *fp;
/*open the file*/
fp = fopen( "/Users/QuantumEh/Documents/datafiles/table.dat", "r" );
/*creates array which allocates appropariate size*/
float *x_axis = (float*) malloc( sizeof( fp ) );
float *y_axis = (float*) malloc( sizeof( fp ) );
if ( fp == NULL ){
printf( "Could not open \n" );
exit( 0 );
}
/*reads in the file*/
while ( fscanf( fp, "%f %f\n", &x_axis[i], &y_axis[i] ) == 2 ){
printf( "%.3f %.3f \n", x_axis[i], y_axis[i] );
i++, n++;
}
/* calculates at one-third and then at two-thirds*/
for ( i = 0; i <= n - 1; i++ ){
x = x_of_interpolation_onethird( x_axis[i + 1], x_axis[i] ); //finds x of interpolation
y = lagrange_interpolation( &x_axis[i], &y_axis[i], x ); //plugs in the orignal x and y and the x of interpolation
x1 = x_of_interpolation_twothird( x_axis[i + 1], x_axis[i] ); //finds the other x of interpolation
y2 = lagrange_interpolation( &x_axis[i], &y_axis[i], x1 ); //plugs in the orignal x and y and the x of interpolation
/* prints out all the numbers*/
//printf("%.3f %.3f \n", x_axis[i], y_axis[i]);
//printf("%.3f \n", x1);
//printf("%.3f %.3f\n", x, y);
}
return 0;
}
答案 0 :(得分:0)
主要问题是使用以下代码 not 确定内存分配所需的浮点值的数量。 fp
的大小与所需的内存无关。
fp = fopen("/Users/QuantumEh/Documents/datafiles/table.dat", "r");
float *x_axis = (float*) malloc(sizeof(fp));
而是使用其他方法。一种方法,一定工作,但有点低效,是读取瓷砖两次。
fp = fopen("/Users/QuantumEh/Documents/datafiles/table.dat", "r");
...
float x,y;
size_t n = 0;
while (fscanf(fp, "%f %f\n", &x, &y) == 2) n++;
float *x_axis = malloc(n * sizeof *x_axis);
float *y_axis = malloc(n * sizeof *y_axis);
rewind(fp);
size_t i = 0;
for (i=0; i<n; i++) {
if (fscanf(fp, "%f %f\n", &x_axis[i], &y_axis[i])!=2) Handle_UnexpectedError();
}
fclose(fp);
// Use x_axis, y_axis
// Be sure to free when done
free(x_axis);
free(y_axis);
注意:未经测试的代码。