长双没有提供所需的精度

时间:2015-12-02 17:47:16

标签: c++ c file floating-accuracy

我正在读取一个文件,该文件的指数值具有7位数的精度值

  

4.81591e-007

     

5.17968e-007

     

5.03954e-008

     

-8.30735e-007

虽然我得到的值只有5点精度

  

0.000000

     

0.000001

     

0.000000

     

-0.000001

     

-0.000002

代码如下,是

#include<iostream>
#include<vector>
#include<utility> 
#include<algorithm>
#include<map>
#include<cmath>
#include<sstream>
#include<string>
#include<queue>
#include<cstdlib>
#include<cstdio>
#include<fstream>
using namespace std;    
int main()
{
    FILE *fp2;
    fp2=fopen("output","w");
    int i=0;
    ifstream myFile;
    myFile.open("sruthi_DATA_.txt");
    vector<long double>numberlist;
    long double number;
    while(myFile >> number){    //
            numberlist.push_back(number);
            i++;
    }
    int j;
    for(j=0;j<i;j++)
    {
        cout.precision(10);
        cout<<numberlist[j]<<fixed<<endl;
        fprintf(fp2,"%Lf\n",numberlist[j]);
    }
    fclose(fp);
    fclose(fp2);

    return 0;

}

3 个答案:

答案 0 :(得分:5)

尝试将值打印为fixed

http://www.cplusplus.com/reference/iomanip/setprecision/
http://www.cplusplus.com/reference/cstdio/printf/

 std::cout << std::fixed << std::setprecision(10) << value << "\n";

定义:

 fixed:       the value is represented with exactly as many digits in
              the decimal part as specified by the precision field
              (precision) and with no exponent part.

 scientific:  as many decimal digits as the precision field
              (precision). Finally, this notation always includes an
              exponential part consisting on the letter e followed by
              an optional sign and three exponential digits.

用C:

打印
  fprintf(fp2, "%.10f\n", value);

格式说明符的定义是:

  %[flags][width][.precision][length]specifier

  Precision: For a, A, e, E, f and F specifiers: this is the number
             of digits to be printed after the decimal point.

因此,为了在C ++中实现与C(%f)相同的格式,您需要使用std::fixed

答案 1 :(得分:2)

如果您希望fprintf在点后打印十位数,则必须在格式化字符串中写入%.10fcout的精确度不会影响fprintf

在数字生效之前,你必须将IO操纵器fixed传递给cout。否则,您打印的第一个号码将不会固定。

cout << fixed << numberlist[j] << endl;

答案 2 :(得分:2)

使用指数表示法(科学)查看C中的数字,小数点后的5个位置使用"%e"

fprintf(fp2,"%.5Le\n",numberlist[j]);
fprintf(fp2,"%.*Le\n", 5, numberlist[j]);
fprintf(fp2,"%.Le\n",numberlist[j]);  // If not precision give, defaults to 6.

要在Printf width specifier to maintain precision中使用

查看FP值
#include <float.h>

fprintf(fp2,"%.*Le\n", LDBL_DECIMAL_DIG - 1, numberlist[j]);
// or simply in hexadecimal notation
fprintf(fp2,"%.*La\n", numberlist[j]);