首页 > 解决方案 > fscanf 不能正确读取双精度

问题描述

我有一个功能

void getXFromFile3(FILE* fptr){
    double valueX;
    fscanf(fptr, "%lf\n", &valueX);
    printf("%lf", valueX);
}

和文件 data.dat 一些双数。

其中之一是-0.572869279,但我的功能 print -0.572869。看来我的号码在某个地方被切断了。

任何想法我做错了什么?

标签: cdoublescanf

解决方案


告诉scanf你它扫描了多少个字符,然后告诉你printf在逗号后打印这个数字。

仍然需要注意逗号前的符号和数字。

下面的代码假定前导零并且输入中没有正号。

void getXFromFile3(FILE* fptr){
  double x;
  int n;
  fscanf(fptr, "%lf%n", &x, &n);
  printf("%.*lf", /* the l length modifier is optional */
   n /* number of characters scanned */
   - (x < 0.) /* one off for the minus sign, if any */
   - ((int)log10(fabs(x)) + 1) /* off as many as digits before the comma */
   - 1, /* one off for the comma */
   x); 
}

胡!;-)


推荐阅读