C++实验: C++工具
1.实验目的
(1)学会使用C++的异常处理机制行程序的调试。
(2)学会使用命名空间解决名字冲突。
2.实验内容
(1)求已知一元二次方程的实根,如果无实根,利用异常处理机制输出警告信息;
(2)已知学生数据管理程序,都用了Student作为类名,调用两个部门的学生数据,分别输出两种内容的学生数据。
3.实验代码
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double q(double, double, double);
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;
return 0;
}
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);
}
header1.h
#include <string>
using namespace std;
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;
}
}
header2.h
#include <string>
using namespace std;
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;
}
}
#include "pch.h"
#include <iostream>
#include "header1.h"
#include "header2.h"
using namespace std;
using namespace student1;
int main()
{
Student stud1(1001, "Wang", 18, "123 Beijing Road,Shanghai");
stud1.show_data();
student2::Student stud2(1102, "Li", 'f', 89.5);
stud2.show_data();
return 0;
}
4.实验结果
(1)


(2)

5.实验总结
1.可以使用C++的异常处理机制进行程序的调试;
2.使用命名空间能够解决名字冲突。
本文介绍了一次C++实验,通过异常处理机制调试求一元二次方程实根的程序,并利用命名空间解决不同部门学生数据管理程序中的名字冲突问题。实验结果显示了异常处理在调试中的应用和命名空间在解决命名冲突上的效果。

3050

被折叠的 条评论
为什么被折叠?



