fscanf()舍入C

时间:2018-03-28 09:22:12

标签: c double scanf rounding precision

我有一个包含这样数字的文件:

0.000000000000000 1
1.274472000000000 0
1.274472708333333 1
1.274472750000000 0
1.274472791666667 1
1.274472833333333 0
1.274472875000000 1

我将对这些数字进行一些计算,所以我用fscanf()读取它们。问题是第一个数字的读取精度非常低。我写了这样的代码:

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

int main(int argc, char** argv)
{
  FILE* tf;
  double t;
  int st;


  tf = fopen(argv[1], "r");
  if(tf == NULL)
    exit(EXIT_FAILURE);
  for(int i=0; i<100; i++)
  {
    fscanf(tf, "%lf %d", &t, &st);
    printf("%lf %d\n", t, st);
  }
  fclose(tf);
  return 0;
}

执行期间读取的值为:

0.000000 1
1.274472 0
1.274473 1
1.274473 0
1.274473 1
1.274473 0
1.274473 1

这显然是不可接受的......任何想法?

2 个答案:

答案 0 :(得分:1)

声明:

fscanf(tf, "%lf %d", &t, &st);

实际上是读完全数。

但是,要让printf()拨打全名(而非默认&#39;精度&#39;),格式说明符%lf需要输出所需的&#39}。精度&#39;上市。即。

printf( "%.16lf %d\n", t, st );

请阅读printf(3)的MAN页面  详情

答案 1 :(得分:-1)

在@Weather Vane&amp; @Michael Walz,我认为你的代码应该是这样的:

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

int main(int argc, char** argv)
{
  FILE* tf;
  double t;
  int st;

  tf = fopen(argv[1], "r");
  if(tf == NULL)
    exit(EXIT_FAILURE);
  /*The ==2  condition will allow reading of the 2 values 
  and at the same time can take care of exceptions if they occur.
  Thus, it smoothly reads the file to it's end, 
  without any need for EOF match OR for looping to match the file size.*/ 
  while(fscanf(tf, "%lf %d", &t, &st)==2)
  {
    //This line will allow the stored number to be presented in a precise form
    printf("%.15lf %d\n", t, st);
  }

  fclose(tf);
  return 0;
}
相关问题