• C++ showpoint操作符(详解版)

    默认情况下,浮点数不会显示尾数 0,并且如果没有小数部分的浮点数则不显示小数点。例如,以下代码:

    double x = 456.0;
    cout << x << endl;

    将仅显示 456。

    现在介绍另一个有用的操作符 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 manipulators
    using 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

    程序的第 10 行中,当第一次打印 x 时,尚未设置任何操作符,由于显示的值不需要小数点,因此只显示数字 6。

    在第 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);

更多...

加载中...