温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

格式化浮点数,C++ format有妙招

发布时间:2024-10-10 19:50:33 来源:亿速云 阅读:78 作者:小樊 栏目:编程语言

在 C++ 中,你可以使用 <iomanip> 库中的 setprecision()setw() 函数来格式化浮点数。以下是一些示例:

  1. 设定小数点后保留的位数
#include <iostream>
#include <iomanip>

int main() {
    double num = 3.1415926;
    std::cout << std::fixed << std::setprecision(2) << num << std::endl; // 输出 3.14
    return 0;
}

在上面的代码中,std::fixed 表示使用固定小数点表示法,std::setprecision(2) 表示小数点后保留两位数字。

  1. 设定字段宽度
#include <iostream>
#include <iomanip>

int main() {
    double num = 3.1415926;
    std::cout << std::setw(10) << std::setprecision(2) << num << std::endl; // 输出 "    3.14"
    return 0;
}

在上面的代码中,std::setw(10) 表示输出宽度为 10 个字符,不足的字符用空格填充。

  1. 结合使用
#include <iostream>
#include <iomanip>

int main() {
    double num = 3.1415926;
    std::cout << std::setw(10) << std::setprecision(2) << std::left << num << std::endl; // 输出 "3.14   "
    return 0;
}

在上面的代码中,std::left 表示左对齐。

希望这些示例对你有所帮助!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI