文档库 最新最全的文档下载
当前位置:文档库 › 第1章 部分习题参考答案

第1章 部分习题参考答案

第1章 部分习题参考答案
第1章 部分习题参考答案

第1章 部分习题参考答案

1.2

【解答】 重点:标准输入输出库函数——标准输入输出

流对象

#include

int main()

{ char name[20];

cout<<”Hello!What’s your name?”<

cin>>name;

cout<

return 0;

}

1.3

const int model = 90; // model is a const const int

v[ ]={1,2,3,4}; // v[i] is a const

const int x; // error: no initializer 未赋初值

void f( )

{

model =200; // error 不能修改常量的值

v[2]++; // error 不能修改常量的值

}

【修改 1】

const int model = 90; // model is a const const int

v[ ]={1,2,3,4}; // v[i] is a const

const int x=0; //赋初值

void f( )

{

cout<

cout<< v[2]<

}

或者 int temp=v[2]+1;

【修改 2】

int *const model=90;

const int* v[]={1,2,3,4};

1.4 int strcmp(const char *, const char *);

【解答】确保函数 strcmp 不会修改参数指针所指向的变量

1.6

【解答】(讲义)

? C++语言是强类型化语言,任何函数在使用以前必须有该函数的原型说明, 以便进行实际参数与形式参数之间的类型匹配检查。

? 函数返回值的类型和函数参数的类型、个数、次序在函数声明,函数定义 和函数调用时必须匹配。

? C++语言的编译器执行上述检查能显著减少很多隐藏的错误。

使用函数原形执行强类型检查。任何函数在使用以前必须有该函数的原型说 明,以便进行实际参数与形式参数之间的类型匹配检查。函数返回值的类型和函 数参数的类型、个数、次序在函数声明,函数定义和函数调用时必须匹配。如果 某个函数的定义和调用与其原型不匹配,那么编译器会指出这种错误,而不用等 到运行程序时才显示错误。

创建带有缺省参数的函数时,应注意:

1、缺省参数值应该代表最常使用的情况。如果在 80~90%的时间里能用上缺 省值,缺省参数才比较有意义。

2、如果给某个参数一个缺省值,那么其后的所有参数都需要赋给缺

省值。

1.8

【解答】

#include

using namespace std;

//Overload max( ) three ways 重载函数名 max 三次

int max(int a,int b);

long max(long a,long b);

double max(double a,double b);

int main()

{ int a1=3,b1=10;

long a2=123456,b2=567893; double

a3=2*10^6,b3=-12.34; cout<<"int"

<

<

cout<<"double"<

据的绝对值

return 0;

}

int max(int a,int b)

{ int c; a>b?c=a:c=b;

return(c);

}

long max(long a,long b)

{ long c; a>b?c=a:c=b;

return(c);

}

double max(double a,double b)

{ double c; a>b?c=a:c=b;

return(c);

}

1.9 要点:申请动态数组

【解答】

// A simple example of new and delete.

#include

namespace std; const int

N=10;

int main( )

{ char *p,q;

int i=0;

p=new char[N]; //allocate memory for a array 为数组分配动态内存空间

if(p==NULL)

{ cout<<"Allocation error\n";

return 1;

}

cin>>q;

while(q!='#')

{ p[i++]=q;

cin>>q;

}

cout<

i=0;

while(i

cout<

cout<

delete [] p; // release memory 释放 new 分配的动态内存空间

return 0;

}

1.10

【解答】

void f(int a[ ],int n, int &max, int &min) {

max=min=a[0];

for(int i=1;i

{

if(max

if (min>a[i]) min=a[i];

}

}

void main( )

{

int a[10]={2,5,3,9,0,8,1,7,6,4};

int max,min;

f(a,10,max,min);

cout<<"Max: "<

cout<<"Min: "<

}

相关文档