14.1 求一元二次方程式ax^2+bx+c=0的实根,如果方程没有实根,则输出有关警告信息。
#include <iostream>
#include <cmath>
using namespace std;
double q(double,double,double);
void main()
{double a,b,c,p,x1,x2;
cout<<"please enter a,b,c:";
cin>>a>>b>>c;
p=-b/(2*a);
try
{x1=p+q(a,b,c);
x2=p-q(a,b,c);
cout<<"x1="<<x1<<endl<<"x2="<<x2<<endl;
}
catch(double d)
{cout<<"a="<<a<<",b="<<b<<",c="<<c<<",disc="<<d<<",error!"<<endl;}
cout<<"end"<<endl;
}
double q(double a,double b,double c)
{double disc;
disc=b*b-4*a*c;
if (disc<0) throw disc;
return sqrt(disc)/(2*a);
}
14.2 将例14.3程序改为下面的程序,请分析执行过程,写出运行结果。并指出由于异常处理而调用了那些析构函数。
#include <iostream>
#include <string>
using namespace std;
class Student
{
public:
Student(int n, string nam)
{
cout << "constructor-" << n << endl;
num = n; name = nam;
}
~Student() { cout << "destructor-" << num << endl; }
void get_data();
private:
int num;
string name;
};
void Student::get_data()
{
if (num == 0) throw num;
else cout << num << " " << name << endl;
cout << "in get_data()" << endl;
}
void fun()
{
Student stud1(1101, "tan");
stud1.get_data();
try
{
Student stud2(0, "Li");
stud2.get_data();
}
catch (int n)
{
cout << "num=" << n << ",error!" << endl;
}
}
int main()
{
cout << "main begin" << endl;
cout << "call fun()" << endl;
fun();
cout << "main end" << endl;
return 0;
}
结果:
main begin
call fun()
constructor-1101
1101 tan
in get_data()
constructor-0
destructor-0
num=0,error!
destructor-1101
main end
14.3 学校的人事部门保存了有关学生的部分数据(学号、姓名、年龄、住址),教务部门也保存了学生的另外一些数据(学号、姓名、性别、成绩),两个部门分别编写了本部门的学生数据管理程序,其中都用了Student作为类名。现在要求在全校的学生数据管理程序中调用这两个部门的学生数据,分别输出两种内容的学生数据。要求用ANSI C++编程,使用命名空间。
main文件
//main file
#include <iostream>
using namespace std;
#include "header1.h"
#include "header2.h"
using namespace std;
using namespace student1;
int main()
{
Student stud1(1001, "Wang", 18, "123 Beijing Road,Shanghua");
stud1.show_data();
student2::Student stud2(1102, "Li", 'f', 89.5);
stud2.show_data();
return 0;
}
header1.h头文件
//header1.h
#include <string>
namespace student1
{
class Student
{
public:
Student(int n, string nam, int a, string addr)
{
num = n; name = nam; age = a; address = addr;
}
void show_data();
private:
int num;
string name;
int age;
string address;
};
void Student::show_data()
{
cout << "num:" << num << " name:" << name << " age:" << age
<< " address:" << address << endl;
}
}
header2.h头文件
//header2.h
#include <string>
namespace student2
{
class Student
{
public:
Student(int n, string nam, char s, float sco)
{
num = n; name = nam; sex = s; score = sco;
}
void show_data();
private:
int num;
string name;
char sex;
float score;
};
void Student::show_data()
{
cout << "num:" << num << " name:" << name << " sex:" << sex
<< " score:" << score << endl;
}
}