gpt4 book ai didi

c++ - 写入文件的 C++ 中双重类型的意外舍入

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:29:44 24 4
gpt4 key购买 nike

我正在开发一个 C++ 程序,其中包含大量 double 类型的数字(数百万和数十亿的值,小数点右侧只有几位)。我正在对这些数字进行计算,然后将结果打印到文本/CSV 文件中。我注意到在文本文件中,我所有的数字似乎都四舍五入(到六位数)。因此,值 13,169,911 在我的输出文件中显示为 13,169,900。

这种四舍五入是否只发生在打印品上?为了获得变量中的全部数字,我是否只需要在写入文件时指定一些内容?我在下面包含了一个写入文件代码的示例:

void PrintPropFinance(vector<PropFinance>& PF, int NumProps, int Iterations, int ForecastLength, 
string CurDeal, string ModelRunID, string ScenName, Assumptions& Ass) {

string filename;
ofstream OutFile;
ostringstream s1;

s1 << BASEPATH << "Output/" << CurDeal << "_" << ModelRunID << "_" <<
ScenName << "_PropFinance" << ".csv";
filename = s1.str();

OutFile.open(filename);

// Put in the column headers first
OutFile << "PropID" << ","
<< "Item" << ","
<< "StartDate" << ","
<< "NumOfPeriod" << ","
<< "Result" << ","
<< "Isap" << ","
<< "CurLoanBal" << ","

for (int i=1; i<=NumProps; ++i) {
// Populate the single-vector variables
OutFile << PF[i].PropID << ","
<< PF[i].Item << ","
<< PF[i].StartDate << ","
<< PF[i].NumOfPeriod << ","
<< PF[i].Result << ","
<< PF[i].Isap << ","
<< PF[i].CurLoanBal << ","
<< endl;
}
OutFile.close();
}

// Prop finance class definition
class PropFinance {
public:
string PropID;
int Item;
string StartDate;

int NumOfPeriod;
string Isap;
double CurLoanBal;
}

最佳答案

问题可能与输出流为 double 产生输出的方式有关:如果 13169911 以“科学计数法”打印,它看起来像1.31699E7。 Excel 会很好地读取此符号,但会为它“看不到”的数字置零,使数字看起来像 13,169,900

要解决此问题,请添加 fixed当您输出 double 以确保打印所有数字时的操纵器:

OutFile << PF[i].PropID << "," 
<< PF[i].Item << ","
<< PF[i].StartDate << ","
<< PF[i].NumOfPeriod << ","
<< fixed << PF[i].Result << ","
<< PF[i].Isap << ","
<< fixed << PF[i].CurLoanBal << ","
<< endl;

关于c++ - 写入文件的 C++ 中双重类型的意外舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18130511/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com