C++ C++;浮点截断&;设置精度逻辑错误

C++ C++;浮点截断&;设置精度逻辑错误,c++,file-io,io,floating-accuracy,truncation,C++,File Io,Io,Floating Accuracy,Truncation,我找了一会儿,在这里找不到答案,但这似乎是一个奇怪的问题。我正在用C++中的FScript库工作。我要做的是从输入文件中获取数据,分配变量,并将其输出到屏幕和输出文件。这是我正在进行的一个项目的全部内容,该项目计算汽车贷款的每月付款,这就是为什么变量的命名方式 我的数据文件如下所示: #include<fstream> #include<iomanip> #include<iostream> using namespace std; int main ()

我找了一会儿,在这里找不到答案,但这似乎是一个奇怪的问题。我正在用C++中的FScript库工作。我要做的是从输入文件中获取数据,分配变量,并将其输出到屏幕和输出文件。这是我正在进行的一个项目的全部内容,该项目计算汽车贷款的每月付款,这就是为什么变量的命名方式

我的数据文件如下所示:
#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.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;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
ifstream din;//这些是我的输入和输出文件
流窦道;
float purchasePrice;//输入文件的第一个数字。
浮动首付;//第二个数字。
float annualInterest;//第三个数字。
浮点numYears;//最后一个数字。
//在此处声明输入/输出文件代码
din>>购买价格>>首付>>年利率>>货币;

您还需要将
fmtflags
设置为
fixed

std::cout << std::fixed << std::setprecision(2) << purchasePrice << "\n";

std::coutfloat通常有24个二进制精度位,这意味着它可以存储大约6个精度的十进制数字,因此,如果您的数字大于100000,您将无法获得任何精度的十进制数字

在这种情况下,您应该使用精度约为15位小数的双精度,而不是浮点


这很可能回答了您的具体问题,但如果这是为了钱,您可能根本不应该使用浮动格式,因为它们不能准确地表示0.01作为一个值,例如,因此您所有的计算都是近似值,在处理钱时,您可能不希望这样。通常,请记住便士/美分/我所说的任何数字n一个整数,请小心:)或者更好,一个专门设计用于处理货币值的类,因为在舍入等方面通常有法律要求。

我将purchasePrice和首付更改为双倍,重新运行程序,得到了完全相同的输出。我想这可能也与浮点数据类型的准确性有关,但这是错误的看起来好像不是这样。好吧,我同意这不是你问题的答案。这可能作为一个评论仍然有效,尽管你非常接近浮点数中可用的精度:)谢谢大卫,这完全解决了我的问题。