C++中使用std::cout修改数字的显示格式

C++中使用std::cout修改数字的显示格式

std::cout 用于写入到标准输出流 。

可以让 cout 以十六进制或八进制方式显示整数。程序清单 27.1 演示了如何使用 cout 以各种格式显
示输入的数字

程序清单 27.1 使用 cout 和控制符以十进制、十六进制和八进制格式显示整数

0: #include <iostream>
1: #include <iomanip>
2: using namespace std;
3:
4: int main()
5: {
6: cout << "Enter an integer: ";
7: int input = 0;
8: cin >> input;
9:
10: cout << "Integer in octal: " << oct << input << endl;
11: cout << "Integer in hexadecimal: " << hex << input << endl;
12:
13: cout << "Integer in hex using base notation: ";
14: cout<<setiosflags(ios_base::hex|ios_base::showbase|ios_base::uppercase);
15: cout << input << endl;
16:
17: cout << "Integer after resetting I/O flags: ";
18: cout<<resetiosflags(ios_base::hex|ios_base::showbase|ios_base::uppercase);
19: cout << input << endl;
20:
21: return 0;
22: }

输出:
Enter an integer: 253
Integer in octal: 375
Integer in hexadecimal: fd
Integer in hex using base notation: 0XFD
Integer after resetting I/O flags: 253
分析:
这个代码示例使用了表 27.2 所示的控制符,以修改 cout 显示用户输入的整数 input 的方式。注意
到第 10 和 11 行使用了控制符 oct 和 hex。第 14 行使用了 setiosflags( )让 cout 以十六进制方式(并使用
大写字母)显示该数字,其结果是 cout 将 253 显示为 OXFD。第 18 行使用了 resetiosflags( ),其效果
是再次使用 cout 显示该整数时,将显示为十进制。要将显示整数时使用的基数改为十进制,也可使用
下面这种方式:

cout << dec << input << endl; // displays in decimal

对于诸如 Pi 等数字,可指定 cout 显示它们时使用的精度(小数点后面的位数),还可指定以定点
表示法或科学表示法显示它们。程序清单 27.2 演示了如何设置这些格式

程序清单 27.2 使用 cout 以定点表示法和科学表示法显示 Pi 和圆面积

0: #include <iostream>
1: #include <iomanip>
2: using namespace std;
3:
4: int main()
5: {
6: const double Pi = (double)22.0 / 7;
7: cout << "Pi = " << Pi << endl;
8:
9: cout << endl << "Setting precision to 7: " << endl;
10: cout << setprecision(7);
11: cout << "Pi = " << Pi << endl;
12: cout << fixed << "Fixed Pi = " << Pi << endl;
13: cout << scientific << "Scientific Pi = " << Pi << endl;
14:
15: cout << endl << "Setting precision to 10: " << endl;
16: cout << setprecision(10);
17: cout << "Pi = " << Pi << endl;
18: cout << fixed << "Fixed Pi = " << Pi << endl;
19: cout << scientific << "Scientific Pi = " << Pi << endl;
20:
21: cout << endl << "Enter a radius: ";
22: double radius = 0.0;
23: cin >> radius;
24: cout << "Area of circle: " << 2*Pi*radius*radius << endl;
25:
26: return 0;
27: }

输出:
Pi = 3.14286
Setting precision to 7:
Pi = 3.142857
Fixed Pi = 3.1428571
Scientific Pi = 3.1428571e+000
Setting precision to 10:
Pi = 3.1428571429e+000
Fixed Pi = 3.1428571429
Scientific Pi = 3.1428571429e+000
Enter a radius: 9.99
Area of circle: 6.2731491429e+002

分析:
输出表明, 第 7 行和第 10 行分别将精度设置为 7 和 10 后, 显示的 Pi 值不同。另外, 控制符 scientific
导致计算得到的圆面积被显示为 6.2731491429e+002。

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值