【问题标题】:Reading Scientific Notation in C用 C 读科学记数法
【发布时间】:2014-06-21 15:17:32
【问题描述】:

我正在尝试读取具有以下内容的文件:

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

但我似乎找不到阅读科学记数法的正确方法。这是我的代码:

#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);
}

我尝试了%f, %g, %d 的多种组合来尝试打印结果,但我永远无法得到正确的结果。

如果有人能指出我正确的方向,我将不胜感激。

【问题讨论】:

  • 不要使用fscanf()解析字符串。

标签: c scientific-notation


【解决方案1】:

你想用%lf作为输入,%e作为科学计数法输出:

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

【讨论】:

    【解决方案2】:

    您可以像这样在转换说明符中使用 a、e、f 或 g:

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

    它们都适用于解析浮点数,但对于双精度数,您需要像这样使用长度修饰符“l”:

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

    要打印值,您可以使用任何说明符,但不需要长度修饰符“l”:

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

    这里有一个非常有用的参考: http://en.cppreference.com/w/c/io/fscanf

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-06
      • 1970-01-01
      • 1970-01-01
      • 2016-02-19
      • 2016-03-04
      • 2017-04-05
      • 1970-01-01
      相关资源
      最近更新 更多