注意:数组的最大值同时存在多个的情况!
(1) 对比FindMax2和FindMax22两个函数的处理,细微差别导致结果不同!
(2) 当数组作为函数形参时,如果是常量数组,则最好添加const
(3) sizeof(arr)/sizeof(int)
(4) 随机数生成:
srand((unsigned)time(NULL));
rand() % randomNum; //生成randomNum以内的随机数
#include "stdafx.h"
#include <process.h>
#include <iostream>
#include "time.h"
using namespace std;
// find the maximum in an array.
int FindMax(const int* pArr, int nLen) //最好加上const
{
if (pArr != NULL)
{
int nMax = pArr[0];
for (int i=1; i<nLen; i++)
{
if (nMax < pArr[i])
{
nMax = pArr[i];
}
}
return nMax;
}
else
return 0;
}
// 找出最大和次大的数
void FindMax2(const int* pArr, int nLen, int* pMax1, int* pMax2) //最好加上const
{
*pMax1 = pArr[0];
*pMax2 = 0;
for (int i=1; i<nLen; i++)
{
if (*pMax1 < pArr[i])
{
*pMax2 = *pMax1;
*pMax1 = pArr[i];
}
else if (*pMax1 > pArr[i]) //与下差别
{
if (*pMax2 < pArr[i])
{
*pMax2 = pArr[i];
}
}
}
}
void FindMax22(const int* pArr, int nLen, int* pMax1, int* pMax2) //最好加上const
{
*pMax1 = pArr[0];
*pMax2 = 0;
for (int i=1; i<nLen; i++)
{
if (*pMax1 < pArr[i])
{
*pMax2 = *pMax1;
*pMax1 = pArr[i];
}
else if (*pMax2 < pArr[i]) //与上差别
{
*pMax2 = pArr[i];
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int randomNum = 60;
srand((unsigned)time(NULL));
int arr[10];
for(int i=0; i<10; i++)
{
arr[i] = rand() % randomNum;
cout << arr[i] << '\t';
}
cout << endl;
int result = FindMax(arr, 10); // nLen = sizeof(arr)/sizeof(int)
cout << "the max num in array is :" << result << endl;
int max1 = 0;
int max2 = 0;
FindMax2(arr, sizeof(arr)/sizeof(int), &max1, &max2);
cout << "the max two is :" << max1 << '\t' << max2 << endl;
//数组的最大值存在多个
int arr2[10] = {3,4,3,1,5,6,9,0,6,9};
for(int i=0; i<10; i++)
{
arr[i] = rand() % randomNum;
cout << arr2[i] << '\t';
}
FindMax2(arr2, sizeof(arr)/sizeof(int), &max1, &max2);
cout << "the max two is :" << max1 << '\t' << max2 << endl;
//函数对于存在大于一个的最大数情况,该函数不满足
FindMax22(arr2, sizeof(arr)/sizeof(int), &max1, &max2);
cout << "the max two is :" << max1 << '\t' << max2 << endl;
system("pause");
return 0;
}