关于精度宽度设置

来源:互联网 发布:砸金蛋抽奖软件 编辑:程序博客网 时间:2024/05/16 18:04

C++的输出格式控制,主要是需要<iomanip>这个头文件。(旧式的C++采用<iomanip.h>。顺便说一句,您应该写#include <iostream>,然后用using namespace std;,

对于浮点数输出来讲,主要需要了解的是三个概念:
(1) 浮点数有三种输出方式。第一种是普通计数法,第二种是科学计数法,第三种是从普通计数法和科学计数法两者选较短的一个为准。默认是第三种方式输出。
(2) 输出宽度。如果指定了宽度,并且输出的字符数没有达到指定宽度,则会用一些字符去填充,默认用空格填充。
(3) 输出精度(这个就是您现在最应该关心的)。对于普通计数法,输出精度就是小数位数。对于科学计数法,输出精度就是有效数字位数。

 

cout << resetiosflags(ios::floatfield) << setw(20) << setiosflags(ios::fixed) << setprecision(3) << -2.77556e-16 << endl;
cout << resetiosflags(ios::floatfield) << setw(20) << setiosflags(ios::scientific) << setprecision(3) << -2.77556e-16 << endl;

输出:

3.1416
3.14159
3.14159
3.141590000
                    -0.000
         -2.776e-016
请按任意键继续. . .

 

#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;

int main( void )
{
    const double value = 12.3456789;
 //无论是有fixed的对小数位数的设置,还是直接对数位的设置都会牵扯到一个四舍五入
    cout << value << endl; // 默认以6精度,所以输出为 12.3457,此精度表示的是整个value值的位数是6位
    cout << setprecision(4) << value << endl; // 改成4精度,所以输出为12.35
    cout << setprecision(8) << value << endl; // 改成8精度,所以输出为12.345679 注意默认和直接set精度都是值整个数的位数,
    cout << fixed << setprecision(4) << value << endl; // 加了fixed意味着是固定点方式显示,所以这里的精度指的是小数位,输出为12.3457
    cout << value << endl; // fixed和setprecision的作用还在,依然显示12.3457
    cout.unsetf( ios::fixed ); // 去掉了fixed, 仅仅去掉了一个fixed的作用,set的作用依然存在,所以精度恢复成整个数值的有效位数,显示为12.35
    cout << value << endl;
    cout.precision( 6 ); // 恢复成原来的样子,输出为12.3457
    cout << value << endl;
 cout<<fixed<<value<<endl;

 system("pause");
 return 0;
}

 

 

 

 

1、简介

函数原型:

template<class Elem>

   T4 setfill(

      Elem _Ch

      );

 功能:

        在预设宽度(setw)中如果已存在没用完的宽度大小,则用设置的字符填充

参数:

      Elem _Ch, 用来被填充的字符

返回值:

      The template manipulator returns an object that, when extracted from or inserted into the stream str, calls str.fill(_Ch), and then returns str. The type Elem must be the same as the element type for the stream str.

要求:

      Header: <iomanip>

      Namespace: std

 

2、范例

#include <iomanip>

#include <iostream>

void main()

{

std::cout << std::setfill('#') << std::setw(5) << "1"    << std::endl;

           std::cout << std::setfill('#') << std::setw(5) << "10"   << std::endl;

std::cout << std::setfill('#') << std::setw(5) << "100"  << std::endl;

std::cout << std::setfill('#') << std::setw(5) << "1000" << std::endl;

}

 

//

// 输出结果:

// ####1

// ###10

// ##100

// #1000

原创粉丝点击