
上面会报错,因为数组s[n]当中,n必须是一个常量,用变量就会报错。













练习如下:
#include<stdio.h>
#include<stdlib.h> //清屏命令在这里。
#include <windows.h> //延时10毫秒-sleep,gotoxy函数
#include <iostream>
#include <conio.h> //getch()----不用按回车,就可以输入字符。
#include <graphics.h> //EasyX库,所使用的!
#include <math.h> //三角函数
using namespace std;
float pingjun(int *a, int n) //数组名,作为参数,很有讲究!
{
float sum = 0;
for (int i = 0; i < n;i++)
{
sum += a[i];
}
return (sum / n);
}
void main()
{
int a[6] = { 1, 2, 3, 4, 5 ,7};
cout << pingjun(a, 6) << endl;
}
image.png
用指针方法:
#include<stdio.h>
#include<stdlib.h> //清屏命令在这里。
#include <windows.h> //延时10毫秒-sleep,gotoxy函数
#include <iostream>
#include <conio.h> //getch()----不用按回车,就可以输入字符。
#include <graphics.h> //EasyX库,所使用的!
#include <math.h> //三角函数
using namespace std;
float pingjun(int *a, int n)
{
float sum = 0;
int *p; //定义指针变量p,指向int型变量
for (p=a; p < (a+n);p++) //参考童晶老师代码,p是地址,
{
sum += *p; //*p代表指针p指向的值!
}
return (sum / n);
}
void main()
{
int a[6] = { 1, 2, 3, 4, 5 ,7};
cout << pingjun(a, 6) << endl;
}
=====================================================================
第二个练习:

答案出来了:

int pingjun(int *a, int n)
{
int *p; //定义指针变量p,指向int型变量
int *q;
int temp;
for (p=a,q=(a+n-1); p < q;p++,q--) //参考童晶老师代码,p是地址,
{
temp = *q;
*q = *p;
*p = temp;
}
for (int i = 0; i < n;i++)
{
cout << a[i] << endl;
}
return 0;
}
void main()
{
int a[6] = { 1, 2, 3, 4, 5 ,7};
cout << pingjun(a, 6) << endl;
cout << a[0]<<a[1]<<a[2]<<a[3]<<a[4] << endl;
}
网友评论