搜档网
当前位置:搜档网 › 解析C++例题代码第9章习题1

解析C++例题代码第9章习题1

解析C++例题代码第9章习题1
解析C++例题代码第9章习题1

第9章习题

【例9-1】

//example9_1.cpp

#include

#include

using namespace std;

int main()

{

float a,b,c;

double x1,x2;

cout<<"请输入一元二次方程的系数a、b和c的值:";

cin>>a>>b>>c;

x1=(-b+sqrt(b*b-4*a*c))/(2*a);

x2=(-b-sqrt(b*b-4*a*c))/(2*a);

cout<<"方程的实根是: x1="<

cin>>a>>b>>c;

try

{

if(0 == b) throw b;// throw表达式中b并无意义,代表float型即可

if((b*b-4*a*c)<0) throw 1.0;// 1.0本身无实际意义,只是代表double型

x1=(-b+sqrt(b*b-4*a*c))/(2*a);

x2=(-b-sqrt(b*b-4*a*c))/(2*a);

cout<<"方程的实根是: x1="<

}

catch(double) //捕获double类型的异常

{

cout<<"开方为负值,方程无解!"<

}

cout<<"程序结束!"<

return 0;

}

【例9-2】

//example9_2.cpp

#include

using namespace std;

class Stack

{

public:

Stack( int capacity=10 );//建立一个空栈,其最大容量的缺省值为10 ~Stack(){delete[] elements;};//析构函数,释放数组资源

bool push( int value );//压栈操作

bool pop(int &top_value);//出栈操作

bool isfull(){return top < maxsize? false : true;};//判断栈是否满bool isempty(){return top ? false : true;}; //判断栈是否空

int size(){ return top; }//返回栈中元素的个数

void display();//显示栈中的全部元素

private:

int top;//栈顶

int * elements;//存放栈中元素的栈数组

int maxsize;//栈可容纳元素的个数

};

Stack:: Stack( int capacity):top(0), maxsize(capacity)

{

elements = new int[capacity];//动态创建栈数组

}

bool Stack::pop( int &top_value )

{

if ( isempty() ) return false; //栈空返回false

top_value = elements[ --top ];

return true; //出栈操作正常返回true

}

bool Stack::push( int value )

{

if ( isfull() ) return false;//栈满则返回false

elements[top++ ] = value;

return true; //压栈操作正常返回true

}

void Stack::display()

{

if ( !size() )

{ cout << "栈中没有元素!\n"; return; }

cout << "(栈中有 " << size() << "个元素)( bottom: ";

for ( int i = 0; i < top; ++i )

cout << elements[i] << " ";

cout << " :top )\n";

}

int main()

{

int i,n;

cout << "请输入需要栈的元素个数:";

cin >>n;

Stack myStack(n);

cout << "请输入压栈元素的个数:";

cin >>n;

for ( i = 1; i <= n; ++i )

myStack.push( i );

myStack.display();

cout << "请输入出栈元素的个数:";

cin >>n;

for ( i = 1; i <= n; ++i )

{ int x;

myStack.pop( x );

}

myStack.display();

return 0;

}

【例9-3】

//example9_3.cpp

#include

#include

#include

using namespace std;

typedef struct zero//声明除数为零异常类型

{string s;}ZERO;

typedef struct negative//声明开方值为负异常类型

{string s;}NEGATIVE;

fun2(int a,int b,int c)//抛出异常的函数

{

ZERO s1;NEGATIVE s2;

s1.s="除数为零";s2.s="开方值为负数";

if(0 == b) throw s1;

if((b*b-4*a*c)<0) throw s2;

return sqrt(b*b-4*a*c);

}

fun1(int a,int b,int c) //捕获异常并重新抛出异常

{

try

{

return(-b+fun2(a,b,c))/(2*a);

}

catch(ZERO)

{

throw;//重新抛出异常

}

}

int main()

{

float a,b,c;

cout<<"请输入一元二次方程的系数abc:";

cin>>a>>b>>c;

try

{

cout<<"方程的一个实根是: x1="<

}

catch(ZERO S1) //捕获除数为零异常,并处理异常

{

cout<

}

catch(NEGATIVE S2)// 捕获开方值为负数异常,并处理异常

{

cout<

}

cout<<"程序结束!"<

return 0;

}

【例9-4】

//example9_4.cpp

#include

using namespace std;

void Fun( void );

class intArray

{

public:

intArray (int n)

{

p = new int[ n ];

cout << "构造intArray,分配具有" <

}

~intArray ()

{

delete[] p;

cout << "析构intArray,释放资源。" << endl;

}

private:

int *p;

};

void Fun()

{

intArray ia(10);

cout<< "在Fun()中抛掷整型异常。" << endl;

throw 1;

}

int main()

{

try

{

cout << "在主函数的try块中调用函数Fun()。" << endl;

Fun();

}

catch( int )

{

cout << "在主函数catch子句捕获到整型异常," ;

cout << "并进行异常处理。"<< endl;

}

cout << "程序结束!" << endl;

return 0;

}

【例9-5】

//example9_5.cpp

#include

#include

using namespace std;

class Excp//声明异常基类

{

public:

static void print( string msg )// 打印错误信息

{

cout<

}

};

class pushOnFull : public Excp//声明栈满异常类

{

public:

pushOnFull( int i ) : tempvalue( i ) { }

int getTempValue() { return tempvalue; }

private:

int tempvalue;//存放异常发生时没有压栈的值

};

class popOnEmpty : public Excp //声明栈空异常类

{ };

class newError : public Excp//声明动态分配内存异常类

{ };

class otherError : public Excp//声明其它异常类

{ };

class Stack

{

public:

Stack( int capacity=10 ) throw (newError);//建立一空栈,其容量的缺省值为10

~Stack(){delete[] elements;};//析构函数,释放数组资源

void push( int value ) throw (pushOnFull);//压栈

void pop(int &top_value) throw (popOnEmpty);//出栈

bool isfull(){return top < maxsize? false : true;};

bool isempty(){return top ? false : true;};

int size(){ return top; }

void display();

private:

int top;//栈顶指针

int * elements;//存放栈中元素的栈数组

int maxsize;//栈可容纳元素的个数

};

Stack:: Stack( int capacity):top(0), maxsize(capacity)

{

elements = new int[capacity];//动态创建栈数组

if(0==elements) throw newError();//如果分配失败,抛出异常}

void Stack::pop( int &top_value )

{

if ( isempty() ) throw popOnEmpty();//栈空,则抛出异常

top_value = elements[ --top ];

}

void Stack::push( int value )

{

if( isfull() )

throw pushOnFull(value);//栈满抛出异常,并将未入栈元素值传送给异常处理

elements[top++ ] = value;

}

void Stack::display()

{

if ( !size() )

{ cout << "栈中已没有元素!\n"; return; }

cout << "(栈中有 " << size() << "个元素)(bottom: ";

for( int i = 0; i < top; ++i )

cout << elements[i] << " ";

cout << ":top)\n";

}

int main()

{

int i,n,count;

try

{

cout << "请输入需要栈的元素个数:";

cin >>n;

Stack myStack(n);

cout << "请输入压栈元素的个数:";

cin >>n;

for ( i = 1; i <= n; count=++i )

myStack.push( i );

myStack.display();

cout << "请输入出栈元素的个数:";

cin >>n;

for ( i = 1; i <= n; count=i++ )

{ int x;

myStack.pop( x );

}

cout << "已出栈"<

}

catch(pushOnFull e)

{

e.print("栈已满!");

cout << "栈中有"<

cout << "值为"<

}

catch(newError)

{ newError::print("给栈分配空间时出错!");

}

catch(popOnEmpty)

{

cout << "已出栈"<

popOnEmpty::print("栈已空!");

}

catch(Excp)

{

Excp::print("程序其它异常在此处理!");

}

return 0;

}

【例9-6】

//example9_6.cpp

#include//标准异常的头文件

#include

#include

using namespace std;

class Array

{

public:

Array(const char *source, int sz)

{

size = sz;

ca = new char[size];

for ( int i = 0; i < size; ++i )

if ( !source )

ca[i] = 0;

else

ca[i] = source[i];

}

char &operator[]( int i ) const

{

if ( i < 0 || i >= size )

{ string es ="数组越界!";

throw out_of_range( es ); //将es字符串传给out_of_range对象。

}

return ca[i];

}

private:

int size;char *ca;

};

int main()

{

try

{

char ca[] = { 'A','B','C','D','E','F'};

Array CA( ca, sizeof(ca)/sizeof(char) );//实例化一个字符数组类

CA[5]='X';//正常访问字符数组类

CA[6]='G';//越界访问数组类将引发异常

return 0;

}

catch ( const out_of_range &excp )

{

cout<< excp.what()<

return -1;

}

}

【例9-7】

//example9_7.cpp

#include

using namespace std;

int main()

{

int num;

cout<< "请输入一个整数(0退出): ";

try

{

while (1)

{

cin>>num;

if (0 == num)

throw 1; //退出循环

cout<< "你输入了整数: " << num << "\n请输入下一个数(0退出): " ; }

}

catch (int )

{

cout<< "程序结束!" <

}

return 0;

}

【例9-8】

//example9_8.cpp

#include

#include

using namespace std;

class A

{

public:

A()

{ cout<<"构造函数执行。"<

cout<<"抛出整型异常。"<

throw 1;

}

~A()

{ cout<<"析构函数执行。"<

}

};

int main()

{

try

{ A *a=new A;

delete a;

}

catch(int)

{ cout<<"异常处理!"<

return 0;

}

【例9-9】

//example9_9.cpp

#include

#include

using namespace std;

class B

{

public:

~B()

{ cout<<"析构函数被调用。\n";

cout<<"析构函数抛出异常。\n";

throw 1;

}

void *operator new(size_t n) throw() { cout<<"new运算符被调用。\n";

return malloc(n);

}

void operator delete(void *p) throw() { cout<<"delete运算符被调用。\n";

if (p != NULL)

free(p);

}

};

int main()

{

B *b = new B;

try

{ delete b;

}

catch(int)

{

cout<<"异常处理!\n";

}

return 0;

}

【例9-10】

//example9_10.cpp

#include//标准异常的头文件

#include

#include

using namespace std;

typedef struct student

{

int num;

char name[20];

float score;

}Student;

class StudentArray

{

public:

StudentArray(int n)

{

capacity=n;

stud = new Student[capacity];

if(0==stud)

throw bad_alloc();//抛出内存分配异常

}

~StudentArray()

{

delete[] stud;

}

void DataInput()

void FileInput() throw (ios_base::failure); //抛出异常的声明

void FileOutput() throw (ios_base::failure);

private:

Student *stud;

int capacity;

};

void StudentArray::DataInput()//从键盘输入学生的数据

{

cout<<"请按学号、姓名、成绩依次输入"<

for(int i=0;i

cin>>stud[i].num>>stud[i].name>>stud[i].score;

}

void StudentArray::FileInput()

{

int i;

ifstream infile("student.dat",ios::binary);

if(!infile)

{

string es ="从文件读数据错!";

throw ios_base::failure( es );

}

for(i=0;i

infile.close();//关闭文件

float sum=0;

for(i=0;i

sum=sum+stud[i].score;

cout<<"学生的平均成绩是:"<

void StudentArray::FileOutput()

{

ofstream outfile("student.dat",ios::binary);

if(!outfile)

{

string es ="向文件写数据错!";

throw ios_base::failure( es );

}

for(int i=0;i

outfile.close();//关闭文件

}

int main()

{

int n;

cout<<"请输入学生人数:";

cin>>n;

try

{

StudentArray studarr(n);

studarr.DataInput();

studarr.FileOutput();

studarr.FileInput();

}

catch(ios_base::failure &excp)

{

cout<

return -1;

}

catch(bad_alloc &excp)

{

cout<

return -1;

}

return 0;

}

相关主题