要求:输入10个数,求最大值,最小值和平均值
我的代码
#include<iostream>
#include<stdlib.h>
using namespace std;
int getMax(int *arr)
{
int temp;
temp = *arr;
//cout << temp << endl;
for(int i=1; i<10; i++)
{
//if(temp < (*arr+i))
if(temp < *(arr+i))
{
//temp = (*arr+i);
temp = *(arr+i);
//cout << temp << endl;
}
}
return temp;
}
int getMin(int *arr)
{
int temp;
temp = arr[0];
for(int i=1; i<10; i++)
{
if(temp > arr[i])
{
temp = arr[i];
}
}
return temp;
}
float getAve(int *arr)
{
float sum = 0;
sum = arr[0];
for(int i=1; i<10; i++)
{
sum += arr[i];
}
return sum/10;
}
int main()
{
int arr[10] = {0};
for(int i=0; i<10; i++)
cin >> arr[i];
//for(int j=0; j<10; j++)
// cout << arr[j] ;
cout << "最大值为:" << getMax(arr) << endl;
cout << "最小值为:" << getMin(arr) << endl;
cout << "平均值为:" << getAve(arr) << endl;
//cout << sizeof(arr)/sizeof(arr[0]) << endl;
system("pause");
return 0;
}
总结
1、指针做形参时,形参arr的地址指向数组arr[0]的地址,*arr == arr[0],注意区别 (*arr+1) 与 *(arr+1),(arr+1) == arr[0]+1,(arr+1) == arr[1];
2、使用for()循环给数组一一赋值;
思考
输入任意个数,如何求平均值?详情自行脑补,以后分解……
求数组长度可用sizeof(arr)/sizeof(arr[0])