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

实验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;

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值