我怎样才能获取浮点值并按 c++(5.0 作为 5.0)打印它

How can I take a float value and print it as it is in c++(5.0 as 5.0)

本文关键字:c++ 作为 打印 获取      更新时间:2023-10-16

在一个问题中,我正在接收这样的输入,我需要按原样输出它们。
例如,我将收到 5.0 作为输入,需要打印 5.0 作为输出,
但它正在打印 5。我使用了不起作用的设置精度
我认为问题是对于像 2.0,3.0,4.0 这样的数字,它在接受输入本身时四舍五入。请帮助我。

查看我的代码:

float n=5.0
//  n*=1.0;
cin>>n;
cout<<setprecision(16);
cout<<n;//its printing 5 here 

/*
I also tried
printf("%f",n);
//but its printing 5.000000
I can't use printf("%.1f",n)<br>
as input can be 5.234 or 4.5687 so making %.1f will not work for others

*/
您可以使用

std::fixed . 这将像printf一样,强制打印所有精确的小数。 这意味着5现在打印5.000000,如果你不介意超过一个不需要的0。

如果您介意,我没有看到很多解决方案,但是使用ostringstreamsprintf将字符串写入内存中,然后在找不到点时附加".0",并打印该字符串。