【C++】设置输出小数点位数

本文通过C++代码示例介绍了如何使用标准库函数setprecision和setiosflags来控制浮点数的输出精度。演示了不同精度设置下浮点数的显示效果,并展示了科学计数法的应用。
#include <iostream.h>
#include <iomanip.h> //要用到格式控制符

void main()
{
double amount = 22.0/7;
cout <<amount <<endl;
cout <<setprecision(0) <<amount <<endl
<<setprecision(1) <<amount <<endl
<<setprecision(2) <<amount <<endl
<<setprecision(3) <<amount <<endl
<<setprecision(4) <<amount <<endl;

cout <<setiosflags(ios::fixed);
cout <<setprecision(8) <<amount <<endl;

cout <<setiosflags(ios::scientific) 

<<amount <<endl;

cout <<setprecision(6); //重新设置成原默认设置
}

运行结果为:
3.14286
3
3
3.1
3.14
3.143
3.14285714

3.14285714e+00


【PS】

cout << value << endl; // 默认以6精度,所以输出为 12.3457
    cout << setprecision(4) << value << endl; // 改成4精度,所以输出为12.35
    cout << setprecision(8) << value << endl; // 改成8精度,所以输出为12.345679
    cout << fixed << setprecision(4) << value << endl; // 加了fixed意味着是固定点方式显示,所以这里的精度指的是小数位,输出为12.3457
    cout << value << endl; // fixed和setprecision的作用还在,依然显示12.3457
    cout.unsetf( ios::fixed ); // 去掉了fixed,所以精度恢复成整个数值的有效位数,显示为12.35 

C++中,设置double类型小数点位数有以下几种常见方法: ### 使用`printf`函数 可以使用`printf`函数结合格式化字符串来控制输出小数点位数。例如,要保留两位小数输出,可以使用`%.2f`的格式: ```cpp #include <stdio.h> int main() { double num = 8.66666; printf("%.2f\n", num); // 保留两位小数输出 return 0; } ``` 此方法在C语言中也常用,使用`scanf`和`printf`可以实现输入和输出的格式化控制,示例如下: ```cpp #include <iostream> #include <stdio.h> // scanf(), printf() using namespace std; int main() { float score_1, score_2, score_3; // 三个成绩 float sum = 0; while (~scanf("%f %f %f", &score_1, &score_2, &score_3)) { sum = (score_1 + score_2 + score_3) / 3.0; printf("%.2f", sum); // 保留两位小数输出 } return 0; } ``` 上述代码通过`printf("%.2f", sum)`实现了保留两位小数输出的功能 [^2]。 ### 使用`std::cout`和`std::setprecision`与`std::fixed` 使用`std::cout`输出时,可以结合`<iomanip>`头文件中的`std::setprecision`和`std::fixed`来控制小数点位数。`std::fixed`指定使用固定点表示法,`std::setprecision`指定小数点后的位数。示例如下: ```cpp #include <iostream> #include <iomanip> int main() { double zzz = 8.66666; std::cout << std::fixed << std::setprecision(2) << zzz << std::endl; // 保留两位小数输出 return 0; } ``` 这种方式可以灵活地控制输出小数位数,并且可以根据需要进行调整。例如,还可以结合`showpoint`等操纵符来显示小数点和尾随零: ```cpp #include <iostream> #include <iomanip> int main() { std::cout << 12345.0 << std::endl; // 输出12345 std::cout << std::setprecision(4) << 3.1415926 << std::endl; // 输出的结果是3.142 std::cout << std::setprecision(3) << 12345.0 << std::endl; // 输出的结果是 "1.23e+004 " std::cout << std::fixed << std::setprecision(2) << 123.456 << std::endl; // 输出的结果是123.46,要进行四舍五入 std::cout << std::showpoint << 12345.0 << std::endl; // 输出12345.00 return 0; } ``` 这里通过`std::fixed`和`std::setprecision`的组合,实现了不同精度和格式的输出 [^3][^4]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值