实验5 数组、指针及引用
【实验目的】
通过本实验,熟练地掌握有关数组、指针方面的编程方法和技巧。
【实验要求】
⑴掌握一维数组的定义、使用的方法;
⑵掌握与数组有关的一些算法;
⑶通过编写程序理解并熟练掌握指针的概念;
⑷理解引用的概念。
【实验内容】
以下程序任选两个
利用指针及函数形式将两个变量值互换。
#include<iostream>
using namespace std;
void swap(int *p1,int *p2){
int t=*p1; *p1=*p2; *p2=t;
}
int main(){
int a,b;
int *p1=&a,*p2=&b;
cout<<"/n/ta="; cin>>a;
cout<<"/tb="; cin>>b;
cout<<"/tBefore swap a="<<a<<", b="<<b<<endl;
if(a<b) swap(p1,p2);
cout<<"/n/tAfter swap a="<<a<<", b="<<b<<endl;
return 0;
}
利用指针及函数形式将从键盘上输入的一组数(以输入0为结束)中高于平均值的数字显示到屏幕。
#include<iostream>
using namespace std;
const int N=100;
void arrin(int *p,int &n){
int x;
n=0;
cout<<"/n/tPlease input No."<<n+1<<" number: "; cin>>x;
while(x!=0){
*(p+n++)=x;
cout<<"/tPlease input No."<<n+1<<" number: ";
cin>>x;
}
}
float arr_int_aver(int *p,int n){
float ave;
int sum=0;
for(int i=0;i<n;i++)
sum+=*(p+i);
ave=(float)sum/n;
cout<<"/tAverage="<<ave<<endl;
return ave;
}
void arr_f(int *p,int n,float ave){
for(int i=0;i<n;i++)
if(*(p+i)>ave){
cout<<"/tNo.";
cout.width(2);
cout<<i<<"; ";
cout.width(5);
cout<<*(p+i)<<endl;
}
}
int main(){
int a[N],n;
float ave;
arrin(a,n); ave=arr_int_aver(a,n); arr_f(a,n,ave);
return 0;
}
利用指针及函数形式测试字符串的长度(不使用测字符串长度的库函数)。
#include<iostream>
#include<cstdio>
using namespace std;
void input(char *p){
printf("/n/tPlease input a string: "); gets(p);
}
void output(char *p){
cout<<"/""<<p<<"/"";
}
void len(char *p){
int i=0;
while (*(p+i++)!='/0');
cout<<"/n/tThe length of string ";
output(p);
cout<<" is "<<i-1<<endl;
}
int main(){
char c[100];
input(c); len(c);
return 0;
}