浮点精度未在字符串中格式化

Float precision not formatting in string

本文关键字:字符串 格式化 精度      更新时间:2023-10-16

当我编写一个简单的wprintf函数并使用动词表示法将一个float数字传递给它时L"%.2f"它只是在屏幕上打印一个" f ",而不是像格式那样0.00的数字。

我希望得到一些帮助,因为无论我在哪里看,它都只是说L"%.2f"是打印具有 2 个十进制数字精度的数字的方法。

float duration = (float)((std::clock() - mTimer) / (float)(CLOCKS_PER_SEC / 1000));
wsprintf(message, L">> Speed: %.2frn", duration);

这是引起我头痛的 2 行...它们导致

>> Speed: f

正在控制台上打印。

我正在寻找的输出是这样的:

>> Speed: 4000.00

函数wsprintf()(似乎是特定于窗口的(不支持浮点参数,你可以改用swprintf()(这是一个标准的库函数(。

此外,wsprintf文档中有一个注释,其中指出:

请勿使用。请考虑改用以下函数之一:StringCbPrintf, StringCbPrintfEx, StringCchPrintf, or StringCchPrintfEx 。请参阅安全注意事项。

你可以做的是:

cout << fixed << setprecision(2) << message << ">> Speed : "<< duration << endl;