
double x = 456.0;
cout << x << endl;
现在介绍另一个有用的 *** 作符 showpoint,它允许这些默认值被覆盖。当使用 showpoint 时,表示打印浮点数的小数点和小数位数,即使显示的数值没有小数点。以下是应用了 showpoint *** 作符的代码示例:
double x = 456.0;
cout << showpoint << x << endl;
456.000
这里之所以显示了 3 个零,是因为如果没有指定所需的小数点位数,则默认显示 6 个有效数。可以将 fixed、showpoint 和 setprecision *** 作符一起使用,以便更好地控制输出的外观,示例如下:double x = 456.0;
cout << fixed << showpoint << setprecision(2) << x << endl;
456.00
下面的程序进一步说明了这些 *** 作符的使用。与 setprecision —样,fixed 和 showpoint *** 作符都将持续有效,直到程序员明确更改它们为止:// This program illustrates the how the showpoint,setprecision,and// fixed manipulators operate both indivIDually and when used together.#include <iostream>#include <iomanip> // header file needed to use stream manipulatorsusing namespace std;int main(){ double x = 6.0; cout << x << endl; cout << showpoint << x << endl; cout << setprecision(2) << x << endl; cout << fixed << x << endl; return 0;}程序输出结果:
6
6.00000
6.0
6.00
在第 11 行中,当第二次打印 x 时,由于已经设置了 showpoint *** 作符,因此会显示小数点并且在后面跟零。但是由于 setprecision *** 作符尚未设置,无法控制要打印多少零,所以按默认的 6 个有效数显示 6.00000。
在第 12 行中,当第三次打印 x 时,setprecision *** 作符已经设置。但是,由于 fixed 尚未设置,而 setprecision(2) 表示应显示两个有效数,所以显示的是 6.0。
最后,在第 13 行中,当打印最后一个 x 时,fixed 和 setprecision *** 作符两者都被设置,指定要打印两位小数,因此显示结果为 6.00。
实际上,当同时使用 fixed 和 setprecision *** 作符时,不需要使用 showpoint *** 作符。来看以下语句:
cout << fixed << setprecision(2);
该语句将在两个小数位前面自动显示一个小数点。不过,许多程序员更喜欢使用以下语句:cout << fixed << showpoint << setprecision(2);
总结以上是内存溢出为你收集整理的C++ showpoint *** 作符(详解版)全部内容,希望文章能够帮你解决C++ showpoint *** 作符(详解版)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)