gpt4 book ai didi

c++ - 将 float 舍入为 2 位小数以将其写入文本文件

转载 作者:行者123 更新时间:2023-11-30 03:59:59 30 4
gpt4 key购买 nike

我正在做一个学校项目,我必须将一个 float 写入一个文本文件。问题是我只想将最多 2 位小数的 float 写入文件。我在互联网上搜索了很多,但只找到了流的“setprecision”函数。

我不能那样做,因为我不想打印它,但我想将它写入一个只有 2 位小数的文件。所以我必须首先将 float 转换为相同的数字但只有 2 位小数,然后我将它放入一个字符串(已经包含其他字符)。然后我将该字符串写入输出文件。

我在“ofstream”的描述中发现了一个方法“precision”,但我认为它不适用于我正在尝试做的事情。(http://www.cplusplus.com/reference/fstream/ofstream/)

有谁知道执行此操作的函数或执行此操作的方式吗?

感谢您的帮助!

最佳答案

I can't do that because I don't want to print it but i want to write it to a file with only 2 decimals.

ostream 不仅仅用于打印。您可以对 ofstream 执行与使用 cout 相同的操作。

std::ofstream fout("out.txt");

fout << std::setprecision(2) << 1.23456;

That function makes a string that contains the price with the name of the article and the rest of the information I want. The function returns that string and then I write that string to the output file

好吧,您可以通过将 ostream 引用传递给函数来编写输出,而不是取回字符串。您还可以让函数在将 float 写入字符串时只进行格式化。 Ostreams 不仅仅用于打印或写入文件:

std::stringstream ss;

ss << std::setprecision(2) << 1.23456;

std::string s = ss.str();

关于c++ - 将 float 舍入为 2 位小数以将其写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26562476/

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