C ++数字精度和fstream截断 [英] C++ precision of numbers and truncation with fstream

查看:296
本文介绍了C ++数字精度和fstream截断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个file.txt有数百个数字。
它们在点后有很多位数(最多20),我需要得到它们所有没有截断,否则它们在以下计算中引入错误。我用matlab做了这些数字,所以它有一个怪异的精度,但现在我必须复制这个行为在我的程序。



我这样做:

  fstream in; 
in.open(file.txt,ios :: in);
long double number;
在>>号码中;

我也试过了

  in.precision(20); 
在>>号码中;

在每个>>操作之前,但它是徒劳的

解决方案

以下在我的系统(Win7,VS2012)上正常工作:

  #include< fstream> 
#include< iostream>

int main(void)
{
std :: ifstream file(test.txt);

long double d = 0;
文件>> d;

std :: cout.precision(20);
std :: cout<< d<< \\\
;


return 0;
}

文本文件:



2.7239385667867091



输出:



2.7239385667867091



< blockquote>

如果这在您的系统上不起作用,那么您需要使用第三方号码库。


I have a file.txt with hundreds of numbers. They have many digits (max 20) after the point and I need to get them all without truncation, otherwise they introduce errors in the following computations. I made these numbers with matlab so it has a monstrous precision but now I must replicate this behaviour in my program.

I've done this way:

 fstream in;
 in.open(file.txt, ios::in);
 long double number;
 in>>number;

I also tried this

 in.precision(20);
 in>>number;

before each ">>" operation but it is vain

解决方案

The following works fine on my system (Win7, VS2012):

#include <fstream>
#include <iostream>

int main (void)
{
    std::ifstream file ("test.txt") ;

    long double d = 0 ;
    file >> d ;

    std::cout.precision (20) ;
    std::cout << d << "\n" ;


    return 0 ;
}

The text file:

2.7239385667867091

The output:

2.7239385667867091

If this doesn't work on your system, then you need to use a third-party number library.

这篇关于C ++数字精度和fstream截断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆