C++程序设计实验报告
学号姓名系别班级计科专教师实验日期同组成员
一、实验编号及名称:实验9 指针与引用
二、实验目的:
1.要求能够使用指针,能够用指针给函数传递参数;
2.理解指针、数组和字符串之间的紧密联系,能够声明和使用字符串数组;
3.掌握引用的语法,用引用传递函数的方法。
三、实验内容及要求
1.P168 ch8_17字符指针的操作
2. P172 ch8_20把一个字符指针数组传递给函数
3. P179 ch8_24(函数指针用作函数参数)计算以0.10为步长,特定范围内的三角函数之和
4.P187 ch9_3给引用赋新值
5.P164 ch8_13用指针实现两个数据交换
P190 ch9_4用引用实现两个数据交换
6. P190 ch9_5 用引用实现函数返回两个值。
四、实验材料、工具、或软件:VC++6.0
五、实验步骤(或记录)
1.
程序如下:
#include<iostream.h>
int main()
{
char buffer[10]="ABC";
char *pc;
pc="hello";
cout<<pc<<endl;
pc++;
cout<<pc<<endl;
cout<<*pc<<endl;
pc=buffer;
cout<<pc;
}
运行的结果:
2.编写的程序如下:
#include<iostream.h>
void Print(char*[],int);
void main()
{ char* pn[]={"Fred","Barney","Wilma","Betty"};
int num =sizeof(pn)/sizeof(char*);
Print(pn,num);
}
void Print(char* arr[], int len)
{ for(int i=0; i<len; i++)
cout <<(int)arr[i] <<" "
<<arr[i] <<endl;
}
运行的结果:
3.程序如下:
#include<iostream.h>
#include<math.h>
double sigma(double(*func)(double),double dl,double du)
{
double dt=0.0;
for(double d=dl; d<du; d+=0.1)
dt+=func(d);
return dt;
}
void main()
{
double dsum;
dsum=sigma(sin,0.1,1.0);
cout<<"the sum of sin from 0.1 to 1.0 is"<<dsum<<endl;
dsum=sigma(cos,0.5,3.0);
cout<<"the sum if cos from 0.5 to 3.0 is"<<endl;
}
运行的结果:
4.程序如下:
运行的结果:
5.程序如下:
(用指针实现)
--------------------Configuration: 1 - Win32 Debug-------------------- Linking...
1.exe - 0 error(s), 0 warning(s)
运行的结果:
(用引用实现)
#include<iostream.h>
void swap(int &x,int &y);
void main()
{
int x=5,y=6;
cout<<"before swap,x:"<<" ,y:"<<y<<endl;
swap(x,y);
cout<<"after swap,x:"<<" ,y:"<<y<<endl;
}
void swap(int &rx,int &ry)
{
int temp=rx;
rx=ry;
ry=temp;
}
运行的结果:
6.程序如下:
#include<iostream.h>
bool Factor(int,int&,int&);
void main()
{
int number,squared,cubed;
bool error;
cout<<"Enter a nuber(0~20):";
cin>>number;
error=Factor(number,squared,cubed);
if (error)
cout<<"Error encoutered?\n";
else{
cout<<"Number:"<<number<<endl;
cout<<"Squared:"<<squared<<endl;
cout<<"Cubed:"<<cubed<<endl;
}
}
bool Factor(int n,int& rSquared,int& rCubed)
{
if(n>20 || n<0)
return true;
rSquared = n*n;
rCubed = n*n*n;
return false;
}
运行的结果:
六、实验存在问题和解决办法
1.
2.
3.
4.
5.
6.
七、意见和建议:
八、教师评语(或成绩)
教师签字:
年月日。