C++实验十 C++工具

知识共享许可协议 版权声明:署名,允许他人基于本文进行创作,且必须基于与原先许可协议相同的许可协议分发本文 (Creative Commons

所使用的开发工具及环境:

PC机一套 Visual Studio 2010

实验要求:

1.硬件基本配置:Intel PentiumIII以上级别的CPU,大于64MB的内存。
2.软件要求:Window 2000操作系统,Visual Studio 6.0或更高版本开发环 境。
3.实验学时:2学时
4.实现实验内容中的题目。
5.写实验报告

实验目的:

1、学会使用C++的异常处理机制进行程序的调试
2、学会使用命名空间解决名字冲突。

实验内容:

三、实验内容

1.读程序,分析结果。

#include<iostream>
using namespace std;
int divid(int a,int b){
  if(b==0) throw 0;
  return a/b;
}

int main(){
int a,b;
cout<<"input a,b:";
		while(cin>>a>>b){	
try{
			int c=divid(a,b);
			cout<<"c="<<c<<endl;
			cout<<"input a,b:";	}catch(int){
	 cout<<"除数为0\n";
	 cout<<"input a,b:";
	}
}
cout<<"程序结束\n";
return 0;
} 

2.读程序,分析结果。

#include<iostream>
using namespace std;
void trigger(int code) 
{ 
   try{ 
      if(code==0){throw code;} 
      if(code==1){throw 'x';} 
      if(code==2){ throw '3.14';}//非法数据当整数
   }catch(int i)
   { 
      cout<<"捕捉到整数"<<i<<endl;
   }catch(...)//其他异常
   { 
      cout<<"默认捕捉"<<endl;
	}
} 

void main() 
{
trigger(0);
trigger(1);
trigger(2);
}

3.求一元二次方程式 的实根,如果方程没有实根,则利用异常处理机制输出有关警告信息。

#include <iostream>
#include <cmath>
using namespace std;
int main(){
	double a, b, c, disc;
	cout<<"Please enter a, b, c: ";
	cin>>a>>b>>c;
	disc=b*b-4*a*c;
	try
	{
		if (disc==0)
			cout<<"x="<<(-1)*b/(2*a)<<endl;
		else if (disc>0)
			cout<<"x1="<<((-1)*b+sqrt(disc))/(2*a)<<", x2="<<((-1)*b-sqrt(disc))/(2*a)<<endl;
		else if (disc<0) throw a;
	}
	catch(double){
		cout<<"Error! No result!"<<endl;
	}
	system("pause");
	return 0;
}

4.学校的人事部门保存了有关学生的部分数据(学号、姓名、年龄、住址),教务部门也保存了学生的另外一些数据(学号、姓名、性别、成绩),两个部门分别编写了本部门的学生数据管理程序,其中都用了Student作为类名。现在要求在全校的学生数据管理程序中调用这两个部门的学生数据,分别输出两种内容的学生数据。要求用ANSI C++编程,使用命名空间。 hearder1.h

#include <iostream>
#include <string>
using namespace std;
namespace student1
{
	class Student{
	public:
		Student(int n, string nam, int a, string ad){
			num=n; name=nam; age=a; addr=ad;
		}
		~Student(){}
		void get_data();
	private:
		int num; 
		string name;
		int age;
		string addr;
	};
	void Student::get_data(){
		cout<<num<<" "<<name<<" "<<age<<" "<<addr<<endl;
	}
};

hearder2.h

#include <iostream>
#include <string>
using namespace std;
namespace student2
{
	class Student{
	public:
		Student(int n, string nam, char s, double sc){
			num=n; name=nam; sex=s; score=sc;
		}
		~Student(){}
		void get_data();
	private:
		int num;
		string name;
		char sex;
		double score;
	};
	void Student::get_data(){
		cout<<num<<" "<<name<<" "<<sex<<" "<<score<<endl;
	}
}

Sy10-4.cpp

#include <iostream>
#include <string>
#include "header1.h"
#include "header2.h"
using namespace std;
using namespace student1;
int main(){
	Student stud1(101, "Zhangsan", 18, "chengdu");
	stud1.get_data();
	student2::Student stud2(102, "Lisi", 'f', 88);
	stud2.get_data();
	system("pause");
	return 0;
}

结果与分析 ( 收获、问题 )

学会了使用C++的异常处理机制进行程序的调试
学会了使用命名空间解决名字冲突。

猜你喜欢

转载自blog.csdn.net/qq_44621510/article/details/93249141