我怎样才能获取浮点值并按 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)
在一个问题中,我正在接收这样的输入,我需要按原样输出它们。
例如,我将收到 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。
如果您介意,我没有看到很多解决方案,但是使用ostringstream
或sprintf
将字符串写入内存中,然后在找不到点时附加".0"
,并打印该字符串。
相关文章:
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 将Ref对象作为类成员
- 虚拟决赛作为安全
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 使用指向成员的指针将成员函数作为参数传递
- 我应该使用什么来代替void作为变体中的替代类型之一
- 何时提供默认参数作为模板参数
- 如何将 I->getType() 作为参数传递给 llvm 中的 CreateCall?
- C++使用数组作为多维数组,尽管将其初始化为带有指针的 1D
- C++匿名结构作为std::映射值
- C++:如何使函数只返回作为列表一部分的字符串
- 如何制作一个将函数作为参数的类方法
- 如何在C++中使用非静态成员函数作为回调函数
- 修改函数中的指针(将另一个指针作为参数传递)
- Clang bug?使用指针作为模板参数
- 函数作为模板参数,是否对返回类型强制约束
- 在C++中传递给函数时,为什么要指定数组大小作为参数
- 为什么 Clang 不允许"and"作为函数名称?
- 为什么 std::function 可以作为 std::not2 的参数?