直接方法有四种:使用 std::fixed 和 std::setprecision 函数。使用 std::to_string。使用 std::round。使用 printf。
如何保留 C++ 小数点后一位
直接方法: 使用 std::fixed 和 std::setprecision 函数。
#include #include using namespace std;int main() { double num = 123.456; // 保留小数点后一位 cout << fixed << setprecision(1) << num << endl; // 输出: 123.5 return 0;}
登录后复制
使用 std::to_string:
#include #include using namespace std;int main() { double num = 123.456; stringstream ss; // 保留小数点后一位 ss << fixed << setprecision(1) << num; string str = ss.str(); cout << str << endl; // 输出: 123.5}
登录后复制
使用 std::round:
立即学习“C++免费学习笔记(深入)”;
#include #include using namespace std;int main() { double num = 123.456; // 四舍五入到小数点后一位 num = round(num * 10) / 10; cout << num << endl; // 输出: 123.5}
登录后复制
使用 printf:
#include #include using namespace std;int main() { double num = 123.456; // 保留小数点后一位 printf("%.1f", num); // 输出: 123.5}
登录后复制
以上就是c++++如何保留小数点后一位的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2459303.html