直接方法有四种:使用 std::fixed 和 std::setprecision 函数。使用 std::to_string。使用 std::round。使用 printf。

如何保留 C++ 小数点后一位
直接方法: 使用 std::fixed 和 std::setprecision 函数。
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double num = 123.456;
// 保留小数点后一位
cout << fixed << setprecision(1) << num << endl; // 输出: 123.5
return 0;
}使用 std::to_string:
#include <iostream>
#include <sstream>
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:
无错试用版,保留了所以商城的基本功能,商品数量限制80件2005V-C更新:更新所有订单功能及一些相应的错误,在线支付加上邮费功能支持在线支付八家银行等接口和可以选择商品图文排列功能,可以后台自由设置,银行接口列表如下:动感在线支付支付宝 网银在线 NPS支付 西部支付 1st-pay在线支付平台 首信易支付 易付通 中国在线支付 环讯IPS支付 不使用在线支付默认管理员帐号:admin密码:ad
0
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double num = 123.456;
// 四舍五入到小数点后一位
num = round(num * 10) / 10;
cout << num << endl; // 输出: 123.5
}使用 printf:
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
double num = 123.456;
// 保留小数点后一位
printf("%.1f\n", num); // 输出: 123.5
}以上就是c++++如何保留小数点后一位的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号