Скачать презентацию CHAPTER 4 Function basic 函数基础 Introduction Functions improve Скачать презентацию CHAPTER 4 Function basic 函数基础 Introduction Functions improve

2b914b48d3bda153a64662f4de26b2ac.ppt

  • Количество слайдов: 87

CHAPTER 4 Function basic 函数基础 Introduction Functions improve clarity and enable software. A function CHAPTER 4 Function basic 函数基础 Introduction Functions improve clarity and enable software. A function performs a particular task and the returns with its solution. In this chapter, we explore the fundamental concepts such as invocation and parameter passing, the iostream library and the preprocessor commands. 函数增加了软件的透明性和重用性。函数用于完成一个特定任务,然后返 回执行结果。 本章讨论函数的基本概念,如函数调用和参数传递。还讨论iostream库的 使用;预处理指令。

4. 1 FUNCTION BASICS Function is a module that organize their information and its 4. 1 FUNCTION BASICS Function is a module that organize their information and its manipulation. • All major application developments and even most simple programs use programming schemes in a modular fashion. • Functions are a crucial component of object-oriented programming.

4. 1 FUNCTION BASICS The act of using a function is referred to as 4. 1 FUNCTION BASICS The act of using a function is referred to as an invocating or call(调用). • A function call others. But a programmer-defined function can not call main function. • A function even call itself, except main function. This process is known as recursion(递归). A function can be passed information to perform its task. • The information is referred to as the function’s parameters or arguments.

4. 1 FUNCTION BASICS main A function call others fun 2 fun 1 fun 4. 1 FUNCTION BASICS main A function call others fun 2 fun 1 fun 3 Recursion fun 4 fun 5 fun 6 fun 7

4. 1 FUNCTION BASICS The act of using a function is referred to as 4. 1 FUNCTION BASICS The act of using a function is referred to as an invocating or call(调用). • A function call others. But a programmer-defined function can not call main function. • A function even call itself, except main function. This process is known as recursion(递归). A function can be passed information to perform its task. • The information is referred to as the function’s parameters or arguments.

// Determines roots of a quadratic equation #include <iostream> #include <string> #include <math. h> // Determines roots of a quadratic equation #include #include #include using namespace std; int main() { cout << "Coefficients for quadratic equation: "; double a, b, c; cin >> a >> b >> c; if ((a != 0) && ((b*b - 4*a*c) > 0)) { double radical = sqrt(b*b - 4*a*c); double root 1 = (-b + radical) / (2*a); double root 2 = (-b - radical) / (2*a); cout<<"The roots of "<

// Determines roots of a quadratic equation #include <iostream> #include <string> #include <math. h> // Determines roots of a quadratic equation #include #include #include using namespace std; int main() { Call library function cout << "Coefficients for quadratic equation: "; double a, b, c; cin >> a >> b >> c; if ((a != 0) && ((b*b - 4*a*c) > 0)) { double radical = sqrt(b*b - 4*a*c); double root 1 = (-b + radical) / (2*a); double root 2 = (-b - radical) / (2*a); cout<<"The roots of "<

4. 1. 1 Interface specification 接口声明 The functions interface : • The type of 4. 1. 1 Interface specification 接口声明 The functions interface : • The type of value ( if any ) that the function will return. • The function’s name • A description of function’s parameters For example int main () double sqrt ( double x )

4. 1. 1 Interface specification 接口声明 The form for the function interface : Function. 4. 1. 1 Interface specification 接口声明 The form for the function interface : Function. Type Function. Name ( Parameter. List )

4. 1. 1 Interface specification 接口声明 The form for the function interface : Function. 4. 1. 1 Interface specification 接口声明 The form for the function interface : Function. Type Function. Name ( Parameter. List ) The type of value that the function returns

4. 1. 1 Interface specification 接口声明 The form for the function interface : Function. 4. 1. 1 Interface specification 接口声明 The form for the function interface : Function. Type Function. Name ( Parameter. List ) Identifier name of function

4. 1. 1 Interface specification 接口声明 The form for the function interface : Function. 4. 1. 1 Interface specification 接口声明 The form for the function interface : Function. Type Function. Name ( Parameter. List ) A description of the form parameters ( if any ) are to take

4. 1. 1 Interface specification 接口声明 The form for the function interface : Function. 4. 1. 1 Interface specification 接口声明 The form for the function interface : Function. Type Function. Name ( Parameter. List ) Parameter. List has the form : Parameter. Declaration, … , Parameter. Declaration

4. 1. 1 Interface specification 接口声明 The form for the function interface : Function. 4. 1. 1 Interface specification 接口声明 The form for the function interface : Function. Type Function. Name ( Parameter. List ) Parameter. List has the form : Parameter. Declaration, … , Parameter. Declaration Description of individual parameters

4. 1. 1 Interface specification 接口声明 The form for the function interface : Function. 4. 1. 1 Interface specification 接口声明 The form for the function interface : Function. Type Function. Name ( Parameter. List ) Parameter. List has the form : Parameter. Declaration, … , Parameter. Declaration Value parameter(值参) has the form : Parameter. Type Parameter. Name

4. 1. 1 Interface specification 接口声明 The form for the function interface : Function. 4. 1. 1 Interface specification 接口声明 The form for the function interface : Function. Type Function. Name ( Parameter. List ) Parameter. List has the form : Parameter. Declaration, … , Parameter. Declaration Value parameter(值参) has the form : Parameter. Type Parameter. Name Type of value which the parameter represents

4. 1. 1 Interface specification 接口声明 The form for the function interface : Function. 4. 1. 1 Interface specification 接口声明 The form for the function interface : Function. Type Function. Name ( Parameter. List ) Parameter. List has the form : Parameter. Declaration, … , Parameter. Declaration Value parameter(值参) has the form : Parameter. Type Parameter. Name Identifier name of parameter

4. 1. 1 Interface specification 接口声明 For example int main () double sqrt ( 4. 1. 1 Interface specification 接口声明 For example int main () double sqrt ( double x )

4. 1. 1 Interface specification 接口声明 For example int main () double sqrt ( 4. 1. 1 Interface specification 接口声明 For example int main () double sqrt ( double x ) The type of value

4. 1. 1 Interface specification 接口声明 For example int main () double sqrt ( 4. 1. 1 Interface specification 接口声明 For example int main () double sqrt ( double x ) The name of function

4. 1. 1 Interface specification 接口声明 For example int main () double sqrt ( 4. 1. 1 Interface specification 接口声明 For example int main () double sqrt ( double x ) Function’s parameters

4. 1. 2 Function prototyping 函数原型 • Interface specification is a header of a 4. 1. 2 Function prototyping 函数原型 • Interface specification is a header of a function. • A function prototype statement is a interface specification followed a semicolon(;). • At least the interface must be specified before a function can be use. It can use a function prototype. • The names of the parameters are not necessary in a function prototype.

4. 1. 2 Function prototyping 函数原型 Function prototype statement Function. Type Function. Name ( 4. 1. 2 Function prototyping 函数原型 Function prototype statement Function. Type Function. Name ( Parameter. List ) ; For example : int Prompt. And. Extract () ; float Circle. Area ( float radius ) ; int max ( int , int ) ; void Show. Order ( char , char ) ;

4. 1. 3 Invocation and flow of control 调用和控制流 Calling function form Function. Name 4. 1. 3 Invocation and flow of control 调用和控制流 Calling function form Function. Name ( Actual. Parameter. List ) ; For example : double radical = sqrt ( b*b – 4* a* c) ; Function definition double sqrt ( double x ) { // … ; return value ; }

4. 1. 3 Invocation and flow of control 调用和控制流 Calling function form Function. Name 4. 1. 3 Invocation and flow of control 调用和控制流 Calling function form Function. Name ( Actual. Parameter. List ) ; For example : double radical = sqrt ( b*b – 4* a* c) head of function The ; Function definition double sqrt ( double x ) { // … ; return value ; }

4. 1. 3 Invocation and flow of control 调用和控制流 Calling function form Function. Name 4. 1. 3 Invocation and flow of control 调用和控制流 Calling function form Function. Name ( Actual. Parameter. List ) ; Call function For example : double radical = sqrt ( b*b – 4* a* c) ; Function definition double sqrt ( double x ) { // … ; return value ; }

4. 1. 3 Invocation and flow of control 调用和控制流 Calling function form Function. Name 4. 1. 3 Invocation and flow of control 调用和控制流 Calling function form Function. Name ( Actual. Parameter. List ) ; Parameter Actual 实际参数 For example : double radical = sqrt ( b*b – 4* a* c) ; Function definition double sqrt ( double x ) { // … ; return value ; }

4. 1. 3 Invocation and flow of control 调用和控制流 Calling function form Function. Name 4. 1. 3 Invocation and flow of control 调用和控制流 Calling function form Function. Name ( Actual. Parameter. List ) ; For example : double radical = sqrt ( b*b – 4* a* c) ; Function definition double sqrt ( double x ) { // … ; return value ; } Formal Parameter 形式参数

4. 1. 3 Invocation and flow of control 调用和控制流 Calling function form Function. Name 4. 1. 3 Invocation and flow of control 调用和控制流 Calling function form Function. Name ( Actual. Parameter. List ) ; Call For example : double radical = sqrt ( b*b – 4* a* c) ; Function definition double sqrt ( double x ) { // … ; return value ; }

4. 1. 3 Invocation and flow of control 调用和控制流 Calling function form Function. Name 4. 1. 3 Invocation and flow of control 调用和控制流 Calling function form Function. Name ( Actual. Parameter. List ) ; Call For example : double radical = sqrt ( b*b – 4* a* c) ; The value of expression Function definition double sqrt ( double x ) { // … ; return value ; }

4. 1. 3 Invocation and flow of control 调用和控制流 Calling function form Function. Name 4. 1. 3 Invocation and flow of control 调用和控制流 Calling function form Function. Name ( Actual. Parameter. List ) ; Return For example : double radical = sqrt ( b*b – 4* a* c) ; Function definition double sqrt ( double x ) { // … ; return value ; }

4. 1. 3 Invocation and flow of control 调用和控制流 Calling function form Function. Name 4. 1. 3 Invocation and flow of control 调用和控制流 Calling function form Function. Name ( Actual. Parameter. List ) ; Return For example : double radical = sqrt ( b*b – 4* a* c) ; Function definition double sqrt ( double x ) { // … ; The value is an expression return value ; }

4. 1. 3 Invocation and flow of control 调用和控制流 Calling function in flow of 4. 1. 3 Invocation and flow of control 调用和控制流 Calling function in flow of control It is known side effect ( 副作用 ). For example : #include The order of evaluation is left to the compiler. void main() { int a=1 ; cout<< "a is " << a++ << " , now a is " << a++ << endl ; return; } Output can be : a is 2 , now a is 1

4. 1. 3 Invocation and flow of control 调用和控制流 Calling function in flow of 4. 1. 3 Invocation and flow of control 调用和控制流 Calling function in flow of control For example : modify #include void main() { int a=1 ; cout << "a is " << a++ ; cout << " , now a is " << a++ << endl ; return; } Output : a is 1 , now a is 2

4. 2 THE PREPROCESSOR 预处理器 The preprocessor • examines file inclusion directives and conditional 4. 2 THE PREPROCESSOR 预处理器 The preprocessor • examines file inclusion directives and conditional compilation directives. 检查文件包含指令和条件编译指令。 • Produce the actual file to be compiled. 产生要编译的实际文件。 • The file produced by the preprocessor is called a translation unit. 预处理器产生的文件称为解释单元。

4. 2. 1 File inclusion directives 文件包含指令 • A file inclusion directive specifies the 4. 2. 1 File inclusion directives 文件包含指令 • A file inclusion directive specifies the name of file. • The file named in the directive replaces the directives itself. • There are two file inclusion directive forms.

4. 2. 1 File inclusion directives 文件包含指令 One of forms # include < filename 4. 2. 1 File inclusion directives 文件包含指令 One of forms # include < filename > • Indicate the file is to be found in one of the standard directories of the system. • For PC-based systems, standard directories are within subdirectories of the directory that contains the compiler.

4. 2. 1 File inclusion directives 文件包含指令 The second form # include 4. 2. 1 File inclusion directives 文件包含指令 The second form # include " filename " Search file: • If the filename is an absolute pathname ( 绝对路径 ) , then the file is taken from that absolute pathname. For example: #include " c: examplesourcesimple. h "

4. 2. 1 File inclusion directives 文件包含指令 The second form # include 4. 2. 1 File inclusion directives 文件包含指令 The second form # include " filename " Search file: • If the filename is an absolute pathname ( 绝对路径 ) , then the file is taken from that absolute pathname. • If an absolute pathname is not specified, then the file is taken from the user’s current directory ( 当前目录 ). For example: #include " My. File. dat "

4. 2. 1 File inclusion directives 文件包含指令 The second form # include 4. 2. 1 File inclusion directives 文件包含指令 The second form # include " filename " Search file: • If the filename is an absolute pathname ( 绝对路径 ) , then the file is taken from that absolute pathname. • If an absolute pathname is not specified, then the file is taken from the user’s current directory ( 当前目录 ). Note: The preprocessor does not consider whether the lines it is creating are legal C++ statements. 预处理器不作语法检查

4. 2. 2 Conditions compilation 条件编译 Macro directives 宏命令 #define Macro. Name String The 4. 2. 2 Conditions compilation 条件编译 Macro directives 宏命令 #define Macro. Name String The Macro. Name is replaced into String.

4. 2. 2 Conditions compilation 条件编译 For example #include < iostream. h > #define 4. 2. 2 Conditions compilation 条件编译 For example #include < iostream. h > #define PI 3. 1415926 void main() { double r , l , s ; cout << " Input radius : " ; cin >> r ; l = 2 * PI * r ; s = PI * r ; cout << "L=“ << l << " n. S = " << s << 'n' ; return ; }

4. 2. 2 Conditions compilation 条件编译 For example comparison #include < iostream. h > 4. 2. 2 Conditions compilation 条件编译 For example comparison #include < iostream. h > #define PI 3. 1415926 const PI = 3. 1415926 ; void main() { double r , l , s ; cout << " Input radius : " ; cin >> r ; l = 2 * PI * r ; s = PI * r ; 111 cout << "L=“ << l << " n. S = " << s << 'n' ; return ; }

4. 2. 2 Conditions compilation 条件编译 Conditions compilation directives 条件编译命令 Form one Form two 4. 2. 2 Conditions compilation 条件编译 Conditions compilation directives 条件编译命令 Form one Form two Form three #ifdef Name Statements 1 #endif #ifndef Name Statements 1 #endif #ifdef Const. Expression Statements 1 #endif #ifdef Name Statements 1 #else Statements 2 #endif #ifndef Name Statements 1 #else Statements 2 #endif #ifdef Const. Expression Statements 1 #else Statements 2 #endif

4. 2. 2 Conditions compilation 条件编译 For example: Object ABC //abc. cpp #include<iostream. h> 4. 2. 2 Conditions compilation 条件编译 For example: Object ABC //abc. cpp #include #define T 1 #define ABC void main() {cout<<"hello!"<

4. 2. 2 Conditions compilation 条件编译 For example: Object ABC 1 //abc. cpp #include<iostream. 4. 2. 2 Conditions compilation 条件编译 For example: Object ABC 1 //abc. cpp #include #define T 1 #define ABC void main() {cout<<"hello!"<

4. 2. 2 Conditions compilation 条件编译 For example: Object ABC 1 #include<iostream. h> //abc. 4. 2. 2 Conditions compilation 条件编译 For example: Object ABC 1 #include //abc. cpp #define T 1 #include #define ABC void main() #define T 1 {cout<<"hello!"<

4. 2. 2 Conditions compilation 条件编译 For example: Object ABC 1 #include<iostream. h> //abc. 4. 2. 2 Conditions compilation 条件编译 For example: Object ABC 1 #include //abc. cpp #define T 1 #include #define ABC void main() #define T 1 {cout<<"hello!"< char *s="good morning!"; void main() {cout<<"hello!"<

4. 3 USING SOFTWARE LIBQARIES 使用软件库 global and nonglobal declaration 全局和非全局声明 • A declaration 4. 3 USING SOFTWARE LIBQARIES 使用软件库 global and nonglobal declaration 全局和非全局声明 • A declaration that can be used throughout a program file is called a global declaration(全局声明). • The collection of all global declarations is called the global namespace( 全局作用域). • Header files that make their declaration globally available have the file extension h. • Header files that place their declarations within a nonglobal namespace do not use any file extension.

NAMESPACE The C++ standard includes the namespace and using mechanisms that allow other namespace NAMESPACE The C++ standard includes the namespace and using mechanisms that allow other namespace to be defined and referenced. Inside a namespace, a collection of classes, functions, objects, types, and other namespace can be declared. 标准C++包含了namespace 和 using 机制,它允许定义和引用其他的 名空间(名字作用域)。在名空间中,可以声明类、函数、对象、类 型和其他名空间的集合。

Definitions The namespaces create virtual packages whose elements can be fully specified to prevent Definitions The namespaces create virtual packages whose elements can be fully specified to prevent name ambiguity. 名空间创建程序包,它的元素可以被完全指明,防止名字的模糊不清。 The syntax for defining a namespace : namespace name { statements | Existing. Name }

Definitions The namespaces create virtual packages whose elements can be fully specified to prevent Definitions The namespaces create virtual packages whose elements can be fully specified to prevent name ambiguity. 名空间创建程序包,它的元素可以被完全指明,防止名字的模糊不清。 The syntax for defining a namespace : namespace name { statements | Existing. Name } Optional identifier name of namespace

Definitions The namespaces create virtual packages whose elements can be fully specified to prevent Definitions The namespaces create virtual packages whose elements can be fully specified to prevent name ambiguity. 名空间创建程序包,它的元素可以被完全指明,防止名字的模糊不清。 The syntax for defining a namespace : namespace name { statements | Existing. Name } Classes, functions, objects, types, and other namespace declaration and definitions

Definitions The namespaces create virtual packages whose elements can be fully specified to prevent Definitions The namespaces create virtual packages whose elements can be fully specified to prevent name ambiguity. 名空间创建程序包,它的元素可以被完全指明,防止名字的模糊不清。 The syntax for defining a namespace : namespace name { statements | Existing. Name } Reference to an existing namespace ( 别名 )

For example A. h B. h class A { // … element 1; element For example A. h B. h class A { // … element 1; element 2; // … }; namespace A { class A { // … element 1; element 2; // … }; Other. Element. A ; } class B { // … element 1; element 3; // … }; namespace B { class B { // … element 1; element 3; // … }; }

Using namespace The using statement is often used with namespace. There are two forms: Using namespace The using statement is often used with namespace. There are two forms: using namespace name : : element

Using namespace The using statement is often used with namespace. There are two forms: Using namespace The using statement is often used with namespace. There are two forms: using namespace name Namespace whose elements are to be part namespace using of current namespace( 当前作用域) name : : element

Using namespace The using statement is often used with namespace. There are two forms: Using namespace The using statement is often used with namespace. There are two forms: using namespace name : : element Namespace being reference Element of namespace to be part of current namespace

# include<iostream. h> namespace car { int model ; int length ; int width # include namespace car { int model ; int length ; int width ; } //名空间定义 namespace plane { int model ; namespace size // 名空间可以嵌套 { int length ; int width ; } } namespace car { char * name ; } //名空间可以随时增加成员 //往上面已经定义的car 空间增加一个成员char*name; namespace c = car ; int Time; //名空间可以有别名,c是car的别名 //一个全局变量,它属于一个默认的全局名空间

void main() { car : : length = 3 ; //使用另一个空间的变量,要显式说明 // width = void main() { car : : length = 3 ; //使用另一个空间的变量,要显式说明 // width = 2 ; //错误, width不是当前名空间的变量 plane : : size : : length = 70 ; //嵌套名空间的使用 cout << "the length of plane is " << plane : : size : : length << endl ; cout << "the length of car is " << car : : length << endl ; cout << "the length of c is " << c : : length << endl ; //用别名访问名空间 int Time = 1996 ; // main 函数中的临时变量 : : Time = 1997 ; //全局名空间的变量,有局部变量冲突时要显式说明 using namespace plane ; //指定以下的变量是属于plane空间的变量 model = 202 ; size : : length = 93 ; //无需再显式说明是plane空间 cout << "In plane space. . . " << endl ; cout << model << endl ; cout << size : : length << endl ; using namespace car ; //指定car名空间 name = "Hello Car" ; //name是属于car空间的变量, 无需再显式声明 cout << "In space of car. . . " << endl ; cout << "the name of car is " << name << endl ; }

4. 4 THE IOSTREAM LIBRARY iostream库 C++ I/O libraries provide an interface between the 4. 4 THE IOSTREAM LIBRARY iostream库 C++ I/O libraries provide an interface between the program and the hardware devices make up the computer system. The interface spans two levels of abstraction : • File low level The stream view allows a program to issue generic I/O requests on flows of data. Requests are translated by compiler into file-level specific action. • Stream higher level The file view captures the important physical characteristics of the actual device.

4. 4 THE IOSTREAM LIBRARY iostream库 ios istream fstreambase ifstream istream_withassign strstreambase istrstream ofstream 4. 4 THE IOSTREAM LIBRARY iostream库 ios istream fstreambase ifstream istream_withassign strstreambase istrstream ofstream strstream iostream_withassign ostream ostrstream constream ostream_withassign

4. 4. 1 Standard streams 标准流 4. 4. 2 Standard error streams object 标准错误流对象 4. 4. 1 Standard streams 标准流 4. 4. 2 Standard error streams object 标准错误流对象 default cin The object of istream_withassign keyboard cout The object of ostream_withassign monitor cerr The object of ostream_withassign monitor clog The object of ostream_withassign printer

4. 4. 1 Standard streams 标准流 4. 4. 2 Standard error streams object 标准错误流对象 4. 4. 1 Standard streams 标准流 4. 4. 2 Standard error streams object 标准错误流对象 Can be redirected to a file default cin The object of istream_withassign keyboard cout The object of ostream_withassign monitor cerr The object of ostream_withassign monitor clog The object of ostream_withassign printer

4. 4. 1 Standard streams 标准流 4. 4. 2 Standard error streams object 标准错误流对象 4. 4. 1 Standard streams 标准流 4. 4. 2 Standard error streams object 标准错误流对象 default cin • Can not be redirected The object of istream_withassign are directed to the monitor keyboard • Insertion requests • No buffering, time critical ( 实时 ) cout The object of ostream_withassign monitor cerr The object of ostream_withassign monitor clog The object of ostream_withassign printer

4. 4. 1 Standard streams 标准流 4. 4. 2 Standard error streams object 标准错误流对象 4. 4. 1 Standard streams 标准流 4. 4. 2 Standard error streams object 标准错误流对象 default cin • Can not be redirected The object of istream_withassign are directed to the monitor keyboard • Insertion requests • buffered error stream cout The object of ostream_withassign monitor cerr The object of ostream_withassign monitor clog The object of ostream_withassign printer

How to redirect ? // Example Can not be redirected #include<iostream. h> • The How to redirect ? // Example Can not be redirected #include • The program is compiled to a void fn ( int a , int b ) exe file { if ( b == 0 ) using be redirected. ” ; cerr << “Zero encountered. The message • connot. DOS command that has else parameter cout << a / b << endl ; to run the program } Such as: void main ( ) { fn ( 20 , 2 ) ; Can be redirected D: >example> abc. dat fn ( 20 , 0 ) ; cout is redirected to abc. dat }

4. 4. 3 The iostream manipulators iostream 操作符 • Some input and output stream 4. 4. 3 The iostream manipulators iostream 操作符 • Some input and output stream manipulators are defined in the iostream library. They are used to adjust the I/O format. • I/O manipulators can occur as the right operand of either an operator << or operator >>.

4. 4. 3 The iostream manipulators iostream 操作符 Purpose Manipulator dec 用十进制显示数值 endl 输出一个换行符并清空流 4. 4. 3 The iostream manipulators iostream 操作符 Purpose Manipulator dec 用十进制显示数值 endl 输出一个换行符并清空流 ends 输出一个空字符( null)并清空流 flush 清空流缓冲器 hex 用十六进制显示数值 oct 用八进制显示数值

4. 4. 3 The iostream manipulators iostream 操作符 #include<iostream. h> void main() { int 4. 4. 3 The iostream manipulators iostream 操作符 #include void main() { int i=10, j=20, k=30; cout << "Dec: " << i << " " << j << " " << k << endl ; cout << "Dec: " << dec << i << " " << j << " " << k << "n" << flush ; cout << "Oct: " << oct << i << " " << j << " " << k << endl ; cout << "Hex: " << hex << i << " " << j << " " << k << endl ; return ; } Output: Dec: Oct: Hex: 10 20 30 12 24 36 a 14 1 e

4. 5 THE IOMANIP LIBRARY iomanip 库 • The iomanip library defines a collection 4. 5 THE IOMANIP LIBRARY iomanip 库 • The iomanip library defines a collection of I/O stream manipulators to modify the behavior of insertions and extractions. • The iomanipulators are defined in the standard header file iomanip. #include < iostream. h > #include < iomanip. h >

Manipulator sew(int w) setfill(int c) left right setbase(int b) fixed scientific showpoint noshowpoint setprecision(int Manipulator sew(int w) setfill(int c) left right setbase(int b) fixed scientific showpoint noshowpoint setprecision(int d) skipws nokipws showpos noshowpos showbase noshowbase boolalpha noboolalpha resetiosflags(log f) Purpose 置显示宽度为 w 置填充字符为 c 靠左显示 靠右显示 置基数为 b 显示 按常用示数法显示浮点数 按科学示数法显示浮点数 用小数点显示浮点数 仅当浮点数小数部分不为 0时才显示小数点 设显示精度位数为 d 提取时忽略空白符 提取包括空白符 显示正数前有 + 正数前没有+ 显示数带基数符,八进制数前置 0,十六进制前置 0 x 显示数不带基数符 用符号 true 和 false 显示逻辑值 用 1 和 0 显示逻辑值 按f指示的标志设置 0 按f指示的标志设置 1

//Example format_1 #include<iostream> #include<iomanip> using namespace std; void main() { cout << //Example format_1 #include #include using namespace std; void main() { cout << "Hello" << endl ; cout << left << setw(10) << setfill('*') << "Hello" << endl ; cout << right << setw(10) << setfill('#') << "Hello" << endl ; return ; } Output: Hello***** #####Hello

//Example format_2 #include<iostream> #include<iomanip> using namespace std; void main() { double x = 20. //Example format_2 #include #include using namespace std; void main() { double x = 20. 0/7 ; cout << x << endl ; cout << setprecision(0) << x << endl << setprecision(1) << x << endl Output: 2. 85714 3 2. 9 2. 86 2. 85714286 1. 23 e-013 << setprecision(2) << x << endl << setprecision(3) << x << endl << setprecision(4) << x << endl ; cout << setiosflags(ios: : fixed) << setprecision(8) << x << endl ; cout << setiosflags(ios: : scientific) << 0. 000000123 << endl ; return ; }

//Example format_3 #include<iostream> #include<iomanip> using namespace std; void main() { int i = 10, //Example format_3 #include #include using namespace std; void main() { int i = 10, j = 20, k = 30 ; cout << showbase ; cout << "Dec: " << i << " " << j << " " << k << endl ; cout << setbase(8) ; cout << "Oct: " << i << " " << j << " " << k << endl ; cout<< setbase(16) ; cout << "Hex: " << i << " " << j << " " << k << endl ; return ; } Output: Dec: 10 20 30 Oct: 012 024 036 Hex: 0 xa 0 x 14 0 x 1 e

//Example format_4 #include < iostream > #include < iomanip > using namespace std ; //Example format_4 #include < iostream > #include < iomanip > using namespace std ; void main() { bool T = true , F = false ; cout << T << "t" << F << endl ; cout << boolalpha << T << "t" << F << endl ; cout << noboolalpha << T << "t" << F << endl ; return ; } Output: 1 true 1 0 false 0

//Example format_5 #include < iostream > #include < iomanip > using namespace std ; //Example format_5 #include < iostream > #include < iomanip > using namespace std ; void main() { char c 1, c 2, c 3, c 4 ; cin >> c 1 ; cout << '[' << c 1 << ']' << endl ; cin >> noskipws >> c 2 ; cout << '[' << c 2 << ']' << endl ; cin >> skipws >> c 3 ; Input: cout << '[' << c 3 << ']' << endl ; Output: cin >> c 4 ; cout << '[' << c 4 << ']' << endl ; return; } a b c d [a] [ ] [b] [c]

4. 6 THE FSTREAM LIBRARY fstream 库 ios istream fstreambase ifstream istream_withassign strstreambase ostream 4. 6 THE FSTREAM LIBRARY fstream 库 ios istream fstreambase ifstream istream_withassign strstreambase ostream istrstream ofstream ostrstream fstream strstream ostream_withassign iostream_withassign constream

// Program 5. 2 Calculates average of file mydata. nbr #include <iostream> #include <fstream> // Program 5. 2 Calculates average of file mydata. nbr #include #include #include using namespace std; int main() { ifstream fin("mydata. nbr"); int Values. Processed = 0; float Value. Sum = 0; float Value; while (fin >> Value) Modify { Value. Sum += Value; ++Values. Processed; } Input a string that is a file name if (Values. Processed > 0) { ofstream fout("average. nbr"); float Average = Value. Sum / Values. Processed; fout << "Average: " << Average << endl; } else cerr << "No list to average" << endl; return 0; }

// Program 5. 3 Prompts user for a file and then calculates // the // Program 5. 3 Prompts user for a file and then calculates // the average of the values in that file // … int main() { cout << "File of values to be averaged: "; string File. Name; cin >> File. Name; ifstream fin(File. Name. c_str()); if (! fin) { cerr << "Cannot open " << File. Name<< " for averaging. "<< endl; exit(1); } int Values. Processed = 0; float Value. Sum = 0; float Value; while (fin >> Value) { Value. Sum += Value; ++Values. Processed; } if (Values. Processed > 0) { float Average = Value. Sum / Values. Processed; cout << "Average of values from " << File. Name<< " is " << Average << endl; } else { cerr << "No values to average in "<< File. Name << endl; exit(1); } return 0; }

4. 6 RANDOM NUMBERS 随机数 The C++ stdlib library ( stdio. h ) provides 4. 6 RANDOM NUMBERS 随机数 The C++ stdlib library ( stdio. h ) provides two functions that are uesful in generating pseudorandom number sequences. rand() no parameters, returns a uniform pseudorandom from inclusive interval 0 to RAND_MAX. srand() expects an unsigned int parameter. The parameter is used to set the seed (启动值) for generating the first pseudorandom number. time() returns a value of type time_t , which is an integral type. It defined in the time library ( time. h ). time(0) returns the current time.

//Program 4. 5: Display ten pseudorandom numbers #include<iostream. h> #include<stdlib. h> #include<time. h> void //Program 4. 5: Display ten pseudorandom numbers #include #include #include void main() { cout<<"Random number seed (number): "; value of seed Input the unsigned int seed; cin>>seed; srand(seed); for(int i=1; i<=10; i++) cout<

//Program 5. 6: Display numbers #include<iostream. h> #include<stdlib. h> #include<time. h> void main() { //Program 5. 6: Display numbers #include #include #include void main() { srand( (unsigned int) time(0) ) ; for ( int i = 1; i <= 10 ; i++ ) cout << rand() << endl ; return; } The value of function time() is used as seed

//using uniform. cpp //uniform. h #ifndef RANDOM_H #define RANDOM_H void Initialize. Seed(); int Uniform(int //using uniform. cpp //uniform. h #ifndef RANDOM_H #define RANDOM_H void Initialize. Seed(); int Uniform(int Low, int High); #endif //Rand. cpp #include #include "uniform. h" void main() { int k, i; for(i=1; i<=10; i++) { k=Uniform(i, i*100); cout< #include #include #include #include "uniform. h" using namespace std; void Initialize. Seed() { srand((unsigned int) time(0)); } int Uniform(int Low, int High) { if (Low > High) {cerr << "Illegal range passed to Uniformn"; exit(1); return 0; } else { int Interval. Size = High - Low + 1; int Random. Offset = rand() % Interval. Size; return Low + Random. Offset; } }

4. 8 THE ASSERT LIBRARY assert库 • assert ( 调试声明 ) is useful during 4. 8 THE ASSERT LIBRARY assert库 • assert ( 调试声明 ) is useful during program development, it is declared in assert library. • The assert macro expects an integral expression as its parameter. • If the expression is: Nonzero the program continues. Zero the program produces message to the standard error, and then , the program terminates.

// Program 5. 7: Computes quotient and remainder of two inputs #include <cassert> #include // Program 5. 7: Computes quotient and remainder of two inputs #include #include #include using namespace std; int main() { int Numerator; cout << "Enter numerator: "; cin >> Numerator; int Denominator; cout << "Enter denominator: "; cin >> Denominator; assert(Denominator); // really should be if test int Ratio = Numerator / Denominator; int Remainder = Numerator % Denominator; cout << Numerator << "/" << Denominator << " = " << Ratio << " with remainder " << Remainder << endl; return 0; }

// Program 5. 7: Computes quotient and remainder of two inputs #include <cassert> #include // Program 5. 7: Computes quotient and remainder of two inputs #include #include #include using namespace std; modify int main() if (Denominator) { int Numerator; cout << "Enter numerator: "; { cerr << " The Denominator is fail. n" ; return 1; cin >> Numerator; } int Denominator; cout << "Enter denominator: "; cin >> Denominator; assert(Denominator); // really should be if test int Ratio = Numerator / Denominator; int Remainder = Numerator % Denominator; cout << Numerator << "/" << Denominator << " = " << Ratio << " with remainder " << Remainder << endl; return 0; }