C++编程实例-数组、指针及引用

实验5 数组、指针及引用

【实验目的】

通过本实验,熟练地掌握有关数组、指针方面的编程方法和技巧。

【实验要求】

⑴掌握一维数组的定义、使用的方法;

⑵掌握与数组有关的一些算法;

⑶通过编写程序理解并熟练掌握指针的概念;

⑷理解引用的概念。

【实验内容】

以下程序任选两个

利用指针及函数形式将两个变量值互换。

#include

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="<

    if(a

    cout<<"/n/tAfter swap   a="<

    return 0;

}

利用指针及函数形式将从键盘上输入的一组数(以输入0为结束)中高于平均值的数字显示到屏幕。

#include

using namespace std;

const int N=100;

void arrin(int *p,int &n){

    int x;

    n=0;

    cout<<"/n/tPlease input No."<>x;

    while(x!=0){

        *(p+n++)=x;

        cout<<"/tPlease input No."<

        cin>>x;

    }

}

float arr_int_aver(int *p,int n){

    float ave;

    int sum=0;

    for(int i=0;i

        sum+=*(p+i);

    ave=(float)sum/n;

    cout<<"/tAverage="<

    return ave;

}

void arr_f(int *p,int n,float ave){

    for(int i=0;i

        if(*(p+i)>ave){

            cout<<"/tNo.";

            cout.width(2);

            cout<

            cout.width(5);

            cout<<*(p+i)<

        }

}

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

#include

using namespace std;

void input(char *p){

    printf("/n/tPlease input a string: "); gets(p);

}

void output(char *p){

    cout<<"/""<

}

void len(char *p){

    int i=0;

    while (*(p+i++)!='/0');

    cout<<"/n/tThe length of string ";

    output(p);

    cout<<" is "<

}

int main(){

    char c[100];

    input(c); len(c);

    return 0;

}

你可能感兴趣的:(C++编程实例)