Reading Scientific Notation in C

我的梦境 提交于 2019-12-10 14:49:01

问题


I am trying to read a file that has the following contents:

1.0000000e+01 2.9265380e+03 5.0821200e+02 4.3231640e+01

2.0000000e+01 1.0170240e+04 9.2798610e+02 4.0723180e+01

3.0000000e+01 2.1486260e+04 1.1832420e+03 1.0328000e+01

4.0000000e+01 3.3835080e+04 1.1882285e+03 -9.3307000e+00

5.0000000e+01 4.5250830e+04 1.0899705e+03 -1.0320900e+01

6.0000000e+01 5.5634490e+04 9.8935650e+02 -9.8019000e+00

7.0000000e+01 6.5037960e+04 8.9134700e+02 -9.8000000e+00

but I can't seem to find a proper way to read the scientific notation. Here is what I have of the code:

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

int main()
{
    // This is the array to store the input
    double time[24], altitude[24], velocity[24], acceleration[24];
    double var1, var2, var3, var4;

    //This is the pointer declaration for opening a file
    FILE * fp = fopen("rocket.txt", "r");

    int i = 0;

    while(fscanf(fp,"%g %f %f %f", &var1, &var2, &var3, &var4) > 0){
        time[i] = var1;
        altitude[i] = var2;
        velocity[i] = var3;
        acceleration[i] = var4;
        printf("Time: %f \n", &time[i]);
        i++;
    }

    printf("Time: %f", &time[0]);

   fclose(fp);

   return(0);
}

I've tried multiple combinations of %f, %g, %d to try and print out the result but I can never get the right thing.

If anyone can point me on the right direction I will greatly appreciate it.


回答1:


What you want to use is %lf for input and %e for output in scientific notation:

scanf("%lf", &input);
printf("%e\n", input); 



回答2:


You could use a, e, f, or g in the conversion specifier like this:

fscanf(fp, "%a", &input); // NOTE: only with C99 compilers
fscanf(fp, "%e", &input);
fscanf(fp, "%f", &input);
fscanf(fp, "%g", &input);

They will all work for parsing floats, but for doubles you will need to use the length modifier "l" like this:

fscanf(fp, "%le", &input);

To print the values, you can use any of the specifiers but you don't need the length modifier "l":

printf("%e ", input);  // or f or g  (or a C99 compilers only)
printf("%le ", input); // produces the same thing

A really helpful reference is here: http://en.cppreference.com/w/c/io/fscanf



来源:https://stackoverflow.com/questions/24342982/reading-scientific-notation-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!