chapter 4 function basic 函数基础 introduction functions improve clarity and enable software. a...
TRANSCRIPT
CHAPTER 4 Function basic 函数基础
Introduction
Functions improve clarity and enable software. A function performs a p
articular 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 com
mands.
函数增加了软件的透明性和重用性。函数用于完成一个特定任务,然后返回执行结果。本章讨论函数的基本概念,如函数调用和参数传递。还讨论 iostream 库的使用;预处理指令。
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 an invocating or call (调用) .
•A function can call others. But a programmer-defined function can not cal
l main function.
• A function even call itself, except main function. This process is known a
s recursion (递归) .
4.1 FUNCTION BASICS
A function can can be passed information to perform its task.
• The information is referred to as the function’s parameters or
arguments.
4.1 FUNCTION BASICS
fun1fun1 fun2fun2 fun3fun3
fun4fun4 fun5fun5 fun6fun6 fun7fun7
mainmain
A function can call others
Recursion
The act of using a function is referred to as an invocating or call (调用) .
•A function can call others. But a programmer-defined function can not cal
l main function.
• A function even call itself, except main function. This process is known a
s recursion (递归) .
4.1 FUNCTION BASICS
A function can 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>
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 root1 = (-b + radical) / (2*a);
double root2 = (-b - radical) / (2*a);
cout<<"The roots of "<<a<<"x**2 + "<<b<<"x + "<<c
<<" are "<<root1<<" and "<<root2<<endl;
}
else cout<< a<<"x**2 + "<<b<<"x + "<<c<<" does not have two real roots"<<endl;
return 0;
}
// Determines roots of a quadratic equation
#include <iostream>
#include <string>
#include <math.h>
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 root1 = (-b + radical) / (2*a);
double root2 = (-b - radical) / (2*a);
cout<<"The roots of "<<a<<"x**2 + "<<b<<"x + "<<c
<<" are "<<root1<<" and "<<root2<<endl;
}
else cout<< a<<"x**2 + "<<b<<"x + "<<c<<" does not have two real roots"<<endl;
return 0;
}
Call library function
The functions interface :
• The type of value ( if any ) that the function will return.
• The function’s name
• A description of function’s parameters
4.1.1 Interface specification 接口声明
For example
int main ()
double sqrt ( double x )
The form for the function interface :
4.1.1 Interface specification 接口声明
FunctionType FunctionName ( ParameterList
)
The form for the function interface :
4.1.1 Interface specification 接口声明
FunctionType FunctionName ( ParameterList
)
The type of value that the
function returns
The form for the function interface :
4.1.1 Interface specification 接口声明
FunctionType FunctionName ( ParameterList )
Identifier name of function
The form for the function interface :
4.1.1 Interface specification 接口声明
FunctionType FunctionName ( ParameterList )
A description of the form
parameters ( if any ) are to
take
The form for the function interface :
4.1.1 Interface specification 接口声明
FunctionType FunctionName ( ParameterList )
ParameterList has the form :
ParameterDeclaration, … , ParameterDeclaration
The form for the function interface :
4.1.1 Interface specification 接口声明
FunctionType FunctionName ( ParameterList )
ParameterList has the form :
ParameterDeclaration, … , ParameterDeclaration
Description of individual parameters
The form for the function interface :
4.1.1 Interface specification 接口声明
FunctionType FunctionName ( ParameterList )
ParameterList has the form :
ParameterDeclaration, … , ParameterDeclaration
Value parameter (值参) has the form :
ParameterType ParameterName
The form for the function interface :
4.1.1 Interface specification 接口声明
FunctionType FunctionName ( ParameterList )
ParameterList has the form :
ParameterDeclaration, … , ParameterDeclaration
Value parameter (值参) has the form :
ParameterType ParameterName
Type of value which the parameter represents
The form for the function interface :
4.1.1 Interface specification 接口声明
FunctionType FunctionName ( ParameterList )
ParameterList has the form :
ParameterDeclaration, … , ParameterDeclaration
Value parameter (值参) has the form :
ParameterType ParameterName
Identifier name of parameter
4.1.1 Interface specification 接口声明
For example
int main ()
double sqrt ( double x )
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 ( double x )
The name of function
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 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 函数原型
For example :
int PromptAndExtract () ;
float CircleArea ( float radius ) ;
int max ( int , int , int ) ;
void ShowOrder ( char , char , char ) ;
FunctionType FunctionName ( ParameterList ) ;
Function prototype statement
4.1.3 Invocation and flow of control 调用和控制流
Calling function form
FunctionName ( ActualParameterList ) ;
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
FunctionName ( ActualParameterList ) ;
For example :
double radical = sqrt ( b*b – 4* a* c) ;
Function definition double sqrt ( double x ){ // … ; return value ;}
The head of function
4.1.3 Invocation and flow of control 调用和控制流
Calling function form
FunctionName ( ActualParameterList ) ;
For example :
double radical = sqrt ( b*b – 4* a* c) ;
Call function
Function definition double sqrt ( double x ){ // … ; return value ;}
4.1.3 Invocation and flow of control 调用和控制流
Calling function form
FunctionName ( ActualParameterList ) ;
For example :
double radical = sqrt ( b*b – 4* a* c) ;
Actual Parameter实际参数
Function definition double sqrt ( double x ){ // … ; return value ;}
4.1.3 Invocation and flow of control 调用和控制流
Calling function form
FunctionName ( ActualParameterList ) ;
For example :
double radical = sqrt ( b*b – 4* a* c) ; Formal Parameter
形式参数
Function definition double sqrt ( double x ){ // … ; return value ;}
4.1.3 Invocation and flow of control 调用和控制流
Calling function form
FunctionName ( ActualParameterList ) ;
For example :
double radical = sqrt ( b*b – 4* a* c) ;
Function definition double sqrt ( double x ){ // … ; return value ;}
CallCall
4.1.3 Invocation and flow of control 调用和控制流
Calling function form
FunctionName ( ActualParameterList ) ;
For example :
double radical = sqrt ( b*b – 4* a* c) ;
Function definition double sqrt ( double xdouble x ){ // … ; return value ;}
CallCall
The value of expression
4.1.3 Invocation and flow of control 调用和控制流
Calling function form
FunctionName ( ActualParameterList ) ;
For example :
double radical = sqrt ( b*b – 4* a* c) ;
Function definition double sqrt ( double x ){ // … ; return value ;}
ReturnReturn
4.1.3 Invocation and flow of control 调用和控制流
Calling function form
FunctionName ( ActualParameterList ) ;
For example :
double radical = sqrt ( b*b – 4* a* c) ;
Function definition double sqrt ( double x ){ // … ; return value ;}
The value is an expression
ReturnReturn
4.1.3 Invocation and flow of control 调用和控制流
Calling function in flow of control
For example :
#include<iostream.h>
void main()
{ int a=1 ;
cout<< "a is " << a++ << " , now a is " << a++ << endl ;
return;
}
a is 2 , now a is 1 Output can be :
It is known side effect ( 副作用
). The order of evaluation is left
to the compiler.
It is known side effect ( 副作用
). The order of evaluation is left
to the compiler.
4.1.3 Invocation and flow of control 调用和控制流
Calling function in flow of control
For example :
#include<iostream.h>
void main()
{ int a=1 ;
return;
}
a is 1 , now a is 2 Output :
modifymodify
cout << "a is " << a++ ;
cout << " , now a is " << a++ << endl ;
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 THE PREPROCESSOR 预处理器
• 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 文件包含指令
• 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.
The second form # include " filename "
4.2.1 File inclusion directives 文件包含指令
Search file:
• If the filename is an absolute pathname ( 绝对路径 ) , then the file is take
n
from that absolute pathname. For example:
#include " c:\example\source\simple.h "
The second form # include " filename "
4.2.1 File inclusion directives 文件包含指令
Search file:
• If the filename is an absolute pathname ( 绝对路径 ) , then the file is take
n
from that absolute pathname.
For example:
#include " MyFile.dat "
• If an absolute pathname is not specified, then the file is taken from the
user’s current directory ( 当前目录 ).
The second form # include " filename "
4.2.1 File inclusion directives 文件包含指令
Search file:
• If the filename is an absolute pathname ( 绝对路径 ) , then the file is take
n
from that absolute pathname.
Note:
The preprocessor does not consider whether the lines it is creating are legal
C++ statements. 预处理器不作语法检查
• If an absolute pathname is not specified, then the file is taken from the
user’s current directory ( 当前目录 ).
4.2.2 Conditions compilation 条件编译
#define MacroName String
The MacroName is replaced into String.
Macro directives 宏命令
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 * r ;
cout << "L=“ << l << " \nS = " << s << '\n' ;
return ;
}
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 * r ;111
cout << "L=“ << l << " \nS = " << s << '\n' ;
return ;
}
comparisoncomparison
const PI = 3.1415926 ;
4.2.2 Conditions compilation 条件编译
Conditions compilation directives 条件编译命令
Form one
#ifdef Name Statements1#endif
#ifdef Name Statements1#else Statements2 #endif
#ifndef Name Statements1#endif
#ifndef Name Statements1#else Statements2 #endif
Form two
#ifdef ConstExpression Statements1#endif
#ifdef ConstExpression Statements1#else Statements2 #endif
Form three
4.2.2 Conditions compilation 条件编译
For example: Object ABC
//abc.cpp
#include<iostream.h>
#define T 1
#define ABC void main()\
{cout<<"hello!"<<s<<endl;return;}
#include "abc.h"
//abc.h
#if T
char *s="good morning!";
ABC
#endif
Continuation character (
续行符 )
4.2.2 Conditions compilation 条件编译
For example: Object ABC
//abc.cpp
#include<iostream.h>
#define T 1
#define ABC void main()\
{cout<<"hello!"<<s<<endl;return;}
#include "abc.h"
//abc.h
#if T
char *s="good morning!";
ABC
#endif
11
4.2.2 Conditions compilation 条件编译
For example: Object ABC
//abc.cpp
#include<iostream.h>
#define T 1
#define ABC void main()\
{cout<<"hello!"<<s<<endl;return;}
#include "abc.h"
//abc.h//abc.h
#if T#if T
char *s="good morning!";char *s="good morning!";
ABCABC
#endif#endif
#include<iostream.h>
#define T 1
#define ABC void main()\
{cout<<"hello!"<<s<<endl;return;}
#if T
char *s="good morning!";
ABC
#endif
11
22
4.2.2 Conditions compilation 条件编译
For example: Object ABC
//abc.cpp
#include<iostream.h>
#define T 1
#define ABC void main()\
{cout<<"hello!"<<s<<endl;return;}
#include "abc.h"
//abc.h
#if T
char *s="good morning!";
ABC
#endif
#include<iostream.h>
#define T 1
#define ABC void main()\void main()\
{cout<<"hello!"<<s<<endl;return;}{cout<<"hello!"<<s<<endl;return;}
#if T
char *s="good morning!";
ABC
#endif
11
#include<iostream.h>
char *s="good morning!";
void main()
{cout<<"hello!"<<s<<endl;return;}
22
global and nonglobal declaration 全局和非全局声明
4.3 USING SOFTWARE LIBQARIES
使用软件库
• A declaration that can be used throughout a program file is called a globa
l declaration (全局声明) .
• The collection of all global declarations is called the global namespace
(全局作用域) .
• Header files that make their declaration globally available have the file e
xtension h .
• Header files that place their declarations within a nonglobal namespace d
o not use any file extension .
NAMESPACE
The C++ standard includes the namespace and using mechanisms that allo
w other namespace to be defined and referenced. Inside a namespace, a col
lection of classes, functions, objects, types, and other namespace can be de
clared.
标准 C++ 包含了 namespace 和 using 机制,它允许定义和引用其他
的名空间(名字作用域)。在名空间中,可以声明类、函数、对象、
类型和其他名空间的集合。
Definitions
The namespaces create virtual packages whose elements can be fully speci
fied to prevent name ambiguity.
名空间创建程序包,它的元素可以被完全指明,防止名字的模糊不清。
namespace name { statements | ExistingName }
The syntax for defining a namespace :
Definitions
The namespaces create virtual packages whose elements can be fully speci
fied to prevent name ambiguity.
名空间创建程序包,它的元素可以被完全指明,防止名字的模糊不清。
namespace name { statements | ExistingName }
The syntax for defining a namespace :
Optional identifier name
of namespace
Definitions
The namespaces create virtual packages whose elements can be fully speci
fied to prevent name ambiguity.
名空间创建程序包,它的元素可以被完全指明,防止名字的模糊不清。
namespace name { statements | ExistingName }
The syntax for defining a namespace :
Classes, functions, objects,
types, and other namespace
declaration and definitions
Definitions
namespace name { statements | ExistingName }
The syntax for defining a namespace :
Reference to an existing nam
espace ( 别名 )
The namespaces create virtual packages whose elements can be fully speci
fied to prevent name ambiguity.
名空间创建程序包,它的元素可以被完全指明,防止名字的模糊不清。
For example
class A{ // … element1;element1; element2; // …};
A.h
B.h
class B{ // … element1;element1; element3; // …};
namespace B
{ class B { // … element1;element1; element3; // … };}
namespace A{ class A { // … element1;element1; element2; // … }; OtherElementA ;OtherElementA ;}
Using namespace
The using statement is often used with namespace. There are two forms:
using namespace name
using namespace name :: element
Using namespace
The using statement is often used with namespace. There are two forms:
using namespace name
using namespace name :: elementNamespace whose elements are to b
e part of current namespace( 当前作用域 )
Using namespace
The using statement is often used with namespace. There are two forms:
using namespace name
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 ; }
namespace plane{ int model ; namespace size // 名空间可以嵌套 { int length ; int width ; }}
namespace car // 名空间可以随时增加成员 { char * name ; } // 往上面已经定义的 car 空间增加一个成员 char*name;
namespace c = car ; // 名空间可以有别名, c 是 car 的别名
int Time;int Time; // 一个全局变量,它属于一个默认的全局名空间
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 int Time = 1996 ; // main 函数中的临时变量 :: Time = 1997 ; // 全局名空间的变量,有局部变量冲突时要显式说明 using namespace plane ; // 指定以下的变量是属于 plane 空间的变量 model model = 202 ; size :: length size :: length = 93 ; // 无需再显式说明是 plane 空间 cout << "In plane space..." << endl ; cout << model << endl ; cout << size :: length << endl ; using namespace car ; // 指定 car 名空间 name name = "Hello Car" ; //name 是属于 car 空间的变量 , 无需再显式声明 cout << "In space of car..." << endl ; cout << "the name of car is " << name name << endl ;}
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 库
4.4 THE IOSTREAM LIBRARY iostream 库
iosiosiosios
istreamistreamistreamistream fstreambasefstreambasefstreambasefstreambase strstreambasestrstreambasestrstreambasestrstreambase ostreamostreamostreamostream
istream_withassignistream_withassignistream_withassignistream_withassign fstreamfstreamfstreamfstream strstreamstrstreamstrstreamstrstream ostream_withassignostream_withassignostream_withassignostream_withassign
iostreamiostreamiostreamiostream
iostream_withassigniostream_withassigniostream_withassigniostream_withassign
ifstreamifstreamifstreamifstream istrstreamistrstreamistrstreamistrstream ofstreamofstreamofstreamofstream ostrstreamostrstreamostrstreamostrstream constreamconstreamconstreamconstream
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
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
Can be redirected to a file
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
• Can not be redirected
• Insertion requests are directed to the monitor
• No buffering, time critical ( No buffering, time critical ( 实时 实时 ))
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
• Can not be redirected
• Insertion requests are directed to the monitor
• buffered error streambuffered error stream
4.4.1 Standard streams 标准流4.4.2 Standard error streams object 标准错误流对象
// Example
#include<iostream.h>
void fn ( int a , int b )
{ if ( b == 0 )
cerr << “Zero encountered. The message connot be redirected.” ;
else
cout << a / b << endl ;
}
void main ( )
{ fn ( 20 , 2 ) ;
fn ( 20 , 0 ) ;
}
Can be redirectedCan be redirected
Can not be redirectedCan not be redirectedHow to redirect ?How to redirect ?
• The program is compiled to a The program is compiled to a
exe fileexe file
• using DOS command that has using DOS command that has
parameter parameter
to run the programto run the program
Such asSuch as ::
D:\>exampleD:\>example> abc.dat> abc.dat
cout is cout is redirected to redirected to abc.databc.dat
How to redirect ?How to redirect ?
• The program is compiled to a The program is compiled to a
exe fileexe file
• using DOS command that has using DOS command that has
parameter parameter
to run the programto run the program
Such asSuch as ::
D:\>exampleD:\>example> abc.dat> abc.dat
cout is cout is redirected to redirected to abc.databc.dat
• Some input and output stream manipulators are defined in the iostream li
brary. 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 操作符
4.4.3 The iostream manipulators iostream 操作符
Manipulator Purpose
dec 用十进制显示数值
endl 输出一个换行符并清空流
ends 输出一个空字符( null )并清空流flush 清空流缓冲器
hex 用十六进制显示数值
oct 用八进制显示数值
4.4.3 The iostream manipulators iostream 操作符
#include<iostream.h>
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 ;
}
Dec: 10 20 30Dec: 10 20 30Oct: 12 24 36Hex: a 14 1e
Output:
• The iomanip library defines a collection of I/O stream manipulators to mo
dify the behavior of insertions and extractions.
• The iomanip manipulators are defined in the standard header file iomanip.
4.5 THE IOMANIP LIBRARY iomanip 库
#include < iostream.h >
#include < iomanip.h >
Manipulator Purposesew(int w) 置显示宽度为 w
setfill(int c) 置填充字符为 c
left 靠左显示right 靠右显示setbase(int b) 置基数为 b 显示fixed 按常用示数法显示浮点数scientific 按科学示数法显示浮点数showpoint 用小数点显示浮点数noshowpoint 仅当浮点数小数部分不为 0 时才显示小数点setprecision(int d) 设显示精度位数为 d
skipws 提取时忽略空白符nokipws 提取包括空白符showpos 显示正数前有 +
noshowpos 正数前没有 +
showbase 显示数带基数符,八进制数前置 0 ,十六进制前置 0x
noshowbase 显示数不带基数符boolalpha 用符号 true 和 false 显示逻辑值noboolalpha 用 1 和 0 显示逻辑值resetiosflags(log f) 按 f 指示的标志设置 0
setiosflags(log f) 按 f 指示的标志设置 1
//Example format_1
#include<iostream>
#include<iomanip>
using namespace std;
void main()
{ cout << "Hello" << endl ;
cout << left << setw(10) << setfill('*') << "Hello" << endl ;
cout << right << setw(10) << setfill('#') << "Hello" << endl ;
return ;
}
HelloHello*****#####Hello
Output:
//Example format_2
#include<iostream>
#include<iomanip>
using namespace std;
void main()
{ double x = 20.0/7 ;
cout << x << endl ;
cout << setprecision(0) << x << endl
<< setprecision(1) << x << endl
<< 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.000000000000123 << endl ;
return ;
}
2.857142.8571432.92.862.8572.857142861.23e-013
Output:
//Example format_3
#include<iostream>
#include<iomanip>
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 ;
} Dec: 10 20 30Oct: 012 024 036Hex: 0xa 0x14 0x1e
Output:
//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 ;
}
1 0true false1 0
Output:
//Example format_5
#include < iostream >
#include < iomanip >
using namespace std ;
void main()
{ char c1, c2, c3, c4 ;
cin >> c1 ;
cout << '[' << c1 << ']' << endl ;
cin >> noskipws >> c2 ;
cout << '[' << c2 << ']' << endl ;
cin >> skipws >> c3 ;
cout << '[' << c3 << ']' << endl ;
cin >> c4 ;
cout << '[' << c4 << ']' << endl ;
return;
}
a b c d[a][ ][b][c]
Input:
Output:
4.6 THE FSTREAM LIBRARY fstream 库
iosiosiosios
istreamistreamistreamistream fstreambasefstreambasefstreambasefstreambase strstreambasestrstreambasestrstreambasestrstreambase ostreamostreamostreamostream
istream_withassignistream_withassignistream_withassignistream_withassign fstreamfstreamfstreamfstream strstreamstrstreamstrstreamstrstream ostream_withassignostream_withassignostream_withassignostream_withassign
iostreamiostreamiostreamiostream
iostream_withassigniostream_withassigniostream_withassigniostream_withassign
ifstreamifstreamifstreamifstream istrstreamistrstreamistrstreamistrstream ofstreamofstreamofstreamofstream ostrstreamostrstreamostrstreamostrstream constreamconstreamconstreamconstream
// Program 5.2 Calculates average of file mydata.nbr#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{ ifstream fin("mydata.nbr");
int ValuesProcessed = 0; float ValueSum = 0; float Value;
while (fin >> Value)
{ ValueSum += Value; ++ValuesProcessed; }
if (ValuesProcessed > 0)
{ ofstream fout("average.nbr");
float Average = ValueSum / ValuesProcessed;
fout << "Average: " << Average << endl;
}
else cerr << "No list to average" << endl;
return 0;
}
ModifyInput a string that is a
file name
// 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 FileName; cin >> FileName; ifstream fin(FileName.c_str()); if (! fin) { cerr << "Cannot open " << FileName<< " for averaging."<< endl; exit(1); } int ValuesProcessed = 0; float ValueSum = 0; float Value; while (fin >> Value) { ValueSum += Value; ++ValuesProcessed; } if (ValuesProcessed > 0) { float Average = ValueSum / ValuesProcessed; cout << "Average of values from " << FileName<< " is " << Average << endl; } else { cerr << "No values to average in "<< FileName << endl; exit(1);} return 0;}
The C++ stdlib library ( stdio.h ) provides two functions that are uesful in
generating pseudorandom number sequences.
4.6 RANDOM NUMBERS 随机数
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 numbe
r. 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 main()
{ cout<<"Random number seed (number):";
unsigned int seed;
cin>>seed;
srand(seed);
for(int i=1;i<=10;i++)
cout<<rand()<<endl;
return;
}
Input the value of seed
//Program 5.6: Display numbers
#include<iostream.h>
#include<stdlib.h>
#include<time.h>
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
//uniform.h
#ifndef RANDOM_H
#define RANDOM_H
void InitializeSeed();
int Uniform(int Low, int High);
#endif
//using uniform.cpp//uniform.cpp#include <iostream>#include <stdlib.h>#include <string>#include <time.h>#include "uniform.h"using namespace std;void InitializeSeed() { srand((unsigned int) time(0)); }int Uniform(int Low, int High) { if (Low > High) {cerr << "Illegal range passed to Uniform\n"; exit(1); return 0; } else { int IntervalSize = High - Low + 1; int RandomOffset = rand() % IntervalSize; return Low + RandomOffset; }}
//Rand.cpp#include<iostream.h>#include "uniform.h"void main(){ int k,i; for(i=1;i<=10;i++) { k=Uniform(i,i*100); cout<<k<<endl; }}
• assert ( 调试声明 ) is useful during program development, it is declar
ed
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.
4.8 THE ASSERT LIBRARY assert 库
// Program 5.7: Computes quotient and remainder of two inputs#include <cassert>
#include <iostream>
#include <string>
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 <iostream>
#include <string>
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;
}
modifyif (Denominator) { cerr << " The Denominator is fail. \n" ; return 1; }