【发布时间】:2012-10-21 03:58:08
【问题描述】:
我找了一会儿,在这里找不到答案,但这似乎是一种奇怪的问题。我正在使用 C++ 中的 fstream 库。我要做的是从输入文件中获取数据,为其分配变量,然后将其输出到屏幕和输出文件。这就是我正在进行的一个计算汽车贷款每月付款的项目的全部内容,这就是变量以它们的方式命名的原因。
我的数据文件如下所示:105670.00 12345.00 0.057 4
基本上正在发生的事情是我丢失了前两个数字的小数点后的所有内容(不管我输入的小数点是什么),但它不会发生在第三个数字上。此外,当我尝试设置前两个数字的精度(2)时,我得到一个奇怪的逻辑错误,我将在我的代码之后显示。
我的代码如下所示:#include<fstream>
#include<iomanip>
#include<iostream>
using namespace std;
int main ()
{
ifstream din; // These are my input and output files
ofstream dout;
float purchasePrice; // The first number of the input file.
float downPayment; // Second number.
float annualInterest; // Third number.
float numYears; // Last number.
// declaring the input/output files code here
din >> purchasePrice >> downPayment >> annualInterest >> numYears;
cout << purchasePrice << endl;
cout << downPayment << endl;
cout << annualInterest << endl;
cout << setprecision(2) << purchasePrice << endl;
cout << setprecision(2) << downPayment << endl;
cout << setprecison(2) << annualInterest << endl;
}
这是我的输出:
105670 12345 0.057 1.1e+005 1.2e+004 0.057
我希望我的输出是:105670.00 12345.00 0.057 105670.00 12345.00 0.05
此外,在执行任何计算时,数字的行为就好像它们仍然具有小数点后的所有内容。我的问题是,为什么只有一些浮点数被截断,为什么 setprecision() 在这种情况下不能按照预期的方式工作?
非常感谢任何回复,很抱歉解释这么长。
【问题讨论】:
标签: c++ file-io io floating-accuracy truncation