C++实验五.docx
《C++实验五.docx》由会员分享,可在线阅读,更多相关《C++实验五.docx(9页珍藏版)》请在冰豆网上搜索。
C++实验五
实验5异常处理
实验课程名:
面向对象程序设计(C++方向)
专业班级:
学号:
姓名:
实验时间:
实验地点:
指导教师:
一、实验目的和要求
(1)正确理解模板的概念。
(2)掌握函数模板和类模板的声明和使用方法。
(3)学习简单的异常处理方法。
二、实验内容
1.分析并调试下列程序,写出运行结果并分析原因。
(1)
//test6_1_1.cpp
#include
usingnamespacestd;
template
Tmax(Tx,Ty)
{returnx>y?
x:
y;
}
intmax(inta,intb)
{returna>b?
a:
b;
}
doublemax(doublea,doubleb)
{returna>b?
a:
b;
}
intmain()
{cout<<”max(‘3’,’7’)is“<return0;
}
(2)
//test6_1_2.cpp
#include
usingnamespacestd;
intmax(inta,intb)
{returna>b?
a:
b;
}
doublemax(doublea,doubleb)
{returna>b?
a:
b;
}
intmain()
{cout<<”max(‘3’,’7’)is“<return0;
}
2.编写一个求任意类型数组中最大元素和最小元素的程序,要求将求最大元素和最小元素的函数设计成函数模板。
程序代码:
#include
usingnamespacestd;
template
Tmaxin(Ta[],intn)
{
Tmax=a[0];
inti;
for(i=1;i{
if(max}
cout<<"数组中最大值为:
"<Tmin=a[0];
for(i=1;i{
if(min>a[i])min=a[i];
}
cout<<"数组中最小值为:
"<return0;
}
intmain()
{
inta[100];
inti,n;
cout<<"请输入数组个数:
";
cin>>n;
for(i=0;i{
cin>>a[i];
}
maxin(a,n);
return0;
}
3.编写一个程序,使用类模板对数组元素进行排序、倒置、查找和求和。
【提示】
设计一个类模板
template
classArray{
...
};
具有对数组元素进行排序、倒置、查找和求和功能,然后产生类型实参分别为int型和double型的两个模板类,分别对整型数组与双精度数组完成所要求的操作。
程序代码:
#include
usingnamespacestd;
template
classArray
{
public:
Array(intx)
{
n=x;
}
numtypesort();
numtypefind();
numtypereserve();
numtypeaccumulate();
numtypedisplay();
numtypeinput();
private:
numtypes[100];
numtypen;
};
//排序
template
numtypeArray:
:
sort()
{
inti,j;
for(i=0;ifor(j=i+1;jif(s[i]>s[j])
{
numtypet;
t=s[i];
s[i]=s[j];
s[j]=t;
}
return0;
}
template
numtypeArray:
:
find()
{
inti;
numtypej;
cout<<"请输入要查找的元素:
";
cin>>j;
for(i=0;i{
if(s[i]==j)
{
cout<<"所查找的元素为:
"<
return0;
}
}
cout<<"没有找到。
"<return0;
}
template
numtypeArray:
:
reserve()
{
inti,j=0;
numtypem;
numtypea[100];
for(i=n-1;i>=0;i--)
{
m=s[i];
a[j]=m;
j++;
}
for(i=0;i{
s[i]=a[i];
}
return0;
}
template
numtypeArray:
:
accumulate()
{
inti;
numtypemax=0;
for(i=0;i{
max=max+s[i];
}
cout<<"求和为:
"<return0;
}
template
numtypeArray:
:
display()
{
inti;
for(i=0;i{
cout<
}
return0;
}
template
numtypeArray:
:
input()
{
inti;
cout<<"请输入"<"<for(i=0;i{
cin>>s[i];
}
return0;
}
intmain()
{
inti;
Arraya(5);
a.input();
a.sort();
cout<<"排序后为:
";a.display();cout<a.find();
a.reserve();
cout<<"倒置后为:
";a.display();cout<a.accumulate();
cout<Arrayb(5);
b.input();
b.sort();
cout<<"排序后为:
";b.display();cout<b.find();
b.reserve();
cout<<"倒置后为:
";b.display();cout<b.accumulate();
cout<return0;
}
4.编写一个程序,求输入数的平方根。
设置异常处理,对输入负数的情况给出提示。
#include
#include
usingnamespacestd;
doublepfg(doublea)
{
doublex;
x=sqrt(a);
returnx;
}
intmain()
{
doublea;
cout<<"请输入一个数:
";
cin>>a;
try
{
while(a>=0)
{
cout<<"平方根为:
"<cout<<"请输入一个数:
";
cin>>a;
}
if(a<0)throwa;
}
catch(double)
{
cout<<"所输入的"<"<}
cout<<"结束"<}
三、结论(写本次实验的收获)