求下面要求的代碼
用函數(shù)的重載完成返回最大值的方法。
現(xiàn)在有一個(gè)數(shù)組,定義一個(gè)方法getMax(),利用函數(shù)的重載,分別實(shí)現(xiàn):
1、隨意取出數(shù)組中的兩個(gè)元素,傳到方法getMax()中,可以返回較大的一個(gè)元素。
2、將整個(gè)數(shù)組傳到方法getMax()中,可以返回?cái)?shù)組中最大的一個(gè)元素。
用函數(shù)的重載完成返回最大值的方法。
現(xiàn)在有一個(gè)數(shù)組,定義一個(gè)方法getMax(),利用函數(shù)的重載,分別實(shí)現(xiàn):
1、隨意取出數(shù)組中的兩個(gè)元素,傳到方法getMax()中,可以返回較大的一個(gè)元素。
2、將整個(gè)數(shù)組傳到方法getMax()中,可以返回?cái)?shù)組中最大的一個(gè)元素。
2017-03-10
舉報(bào)
2017-03-11
#include <iostream>
using namespace std;
/**
? *函數(shù)功能:返回a和b的最大值
? *a和b是兩個(gè)整數(shù)
? */
int getMax(int a, int b)
{
? ? return a > b ? a : b;
}
/**
? * 函數(shù)功能:返回?cái)?shù)組中的最大值
? * arr:整型數(shù)組
? * count:數(shù)組長度
? * 該函數(shù)是對(duì)上面函數(shù)的重載
? */
int getMax(int arr[],int count)
{
? ? //定義一個(gè)變量并獲取數(shù)組的第一個(gè)元素
? ? int a = arr[0];
for(int i = 1; i < count; i++)
{
? ? ? ? //比較變量與下一個(gè)元素的大小
if(arr[i] > a)
{
? ? ? ? ? ? //如果數(shù)組中的元素比maxNum大,則獲取數(shù)組中的值
a = arr[i];
}
}
return a;
}
int main(void)
{
? ? //定義int數(shù)組并初始化
int numArr[3] = {3, 8, 6};
? ??
? ? //自動(dòng)調(diào)用int getMax(int a, int b)
cout << getMax(numArr[0],numArr[1] ) << endl;
? ??
? ? //自動(dòng)調(diào)用返回?cái)?shù)組中最大值的函數(shù)返回?cái)?shù)組中的最大值
cout << getMax(numArr,3) << endl;
return 0;
}