在 C++ 中将双精度数转换为固定小数点
我在 C++ 中有一个双精度变量,想要将其作为固定小数点数字打印到屏幕上。
基本上我想知道如何编写一个函数,该函数采用双精度数和小数位数,并将数字打印到小数位数,必要时用零填充。
例如:
convert(1.235, 2)
will print out
1.24
和
convert(1, 3)
will print out ,
1.000
因此该函数的工作原理
convert(number as double, number of decimal places)
是简单地将所需的值打印到标准输出(cout)。
有谁知道该怎么做?
提前致谢。
I have a double variable in C++ and want to print it out to the screen as a fixed decimal point number.
Basically I want to know how to write a function that takes a double and a number of decimal places and prints out the number to that number of decimal places, zero padding if necessary.
For example:
convert(1.235, 2)
would print out
1.24
and
convert(1, 3)
would print out
1.000
so the function works as
convert(number as double, number of decimal places)
and simply prints out the required value to standard output (cout).
Does anyone know how to do this?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不存在“固定小数位”的数字。转换函数需要是实际打印出来的函数。我建议获取数字的整个部分,然后打印它。如果 [小数位]>0 则打印小数位,然后单独打印每个小数,如:
floor((n*log(10,d))%10);
<-- 只是一个想法,而不是实际代码。There is no such thing as a "fixed decimal place" number. The convert function will need to be the function that actually prints it out. I would suggest getting the whole part of the number, then print it. If [decimal places]>0 then print a decimal place, then print each decimal individually like:
floor((n*log(10,d))%10);
<-- just an idea, not actual code.输出:1.23
参考
output: 1.23
reference
假设我正确记住了我的格式字符串,
Assuming I'm remembering my format strings correctly,
查看 set precision 操纵器 它应该会给你这个想法
Look at the setprecision manipulator which should give you the idea