C语言 在我的代码中打印额外的2行



当我在文档中输入值并从同一循环中将它们打印出来时,我打印出了正确的值。然而,当我在数组中放置值后将它们放入另一个循环中,大约进行了一半,我得到了错误的值,其余的都同意。谢谢你的帮助!

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 %fn", &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 %.3fn", x, y);

    }

    return 0;
}

主要问题是使用下面的代码不能确定内存分配所需的浮点值的数量。fp的大小与所需的内存无关。

fp = fopen("/Users/QuantumEh/Documents/datafiles/table.dat", "r");
float *x_axis = (float*) malloc(sizeof(fp));

请使用其他方法。有一种方法肯定是有效的,但效率有点低,那就是读取该tile两次。

fp = fopen("/Users/QuantumEh/Documents/datafiles/table.dat", "r");
...
float x,y;
size_t n = 0;
while (fscanf(fp, "%f %fn", &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 %fn", &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);

相关内容

  • 没有找到相关文章

最新更新