gpt4 book ai didi

c++ - std::to_string 在转换浮点值时是否保证包含小数点?

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

使用下面的代码,

int main() {
for(;;) {
float d;
cin >> d;
cout << std::to_string(d) << endl;
}
}

to_string 似乎总是返回一个包含小数点后跟六位数字的字符串。此行为是否得到保证(不包括 naninfinity)?

根据 cplusplus.com , "根据需要写入尽可能多的数字来表示整数部分,后跟小数点字符和六位十进制数字"。

最佳答案

to_string seems to always return a string containing a decimal point followed by six digits. Is this behavior guaranteed (excluding nan and infinity)?

是的。 std::to_string 的输出由输出 std::sprintf 控制,其默认精度为 6。

来自 http://en.cppreference.com/w/cpp/string/basic_string/to_string ,

7,8) Converts a floating point value to a string with the same content as what std::sprintf(buf, "%f", value) would produce for sufficiently large buf.

来自 http://en.cppreference.com/w/cpp/io/c/fprintf , (强调我的)

f, F

converts floating-point number to the decimal notation in the style [-]ddd.ddd.

Precision specifies the minimum number of digits to appear after the decimal point character. The default precision is 6.


警告

小数点并非在所有语言环境中都用作小数点标记。根据区域设置,您可能会得到不同的小数点字符。但是无论语言环境如何,都会有一个小数点标记。

关于c++ - std::to_string 在转换浮点值时是否保证包含小数点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29247777/

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