課程
/后端開發
/C++
/C++遠征之離港篇
函數重載沒辦法實現啊,什么問題呀
2017-10-06
源自:C++遠征之離港篇 4-4
正在回答
同學這是網站設計的原因,他有提示你用maxNum做變量,所以你用tem做變量雖然編程沒問題,但是網站不是編譯器,與事先答案比較發現變量名不一樣就判斷你錯誤。而且你也要將函數定義中的*a改成*arr,這不是你的代碼有問題,是因為網站不是編譯器只會和答案比較找錯的原因。(附上我的代碼供你參考,我這個它就認為正確通過了)
#include <iostream>
using namespace std;
/**
? *函數功能:返回a和b的最大值
? *a和b是兩個整數
? */
int getMax(int a, int b)
{
? ? return a > b ? a : b;
}
? * 函數功能:返回數組中的最大值
? * arr:整型數組
? * count:數組長度
? * 該函數是對上面函數的重載
int getMax(int *arr, int count)
? ? //定義一個變量并獲取數組的第一個元素
? ? int maxNum = arr[0];
for(int i = 1; i < count; i++)
? ? ? ? //比較變量與下一個元素的大小
if(arr[i] > maxNum)
? ? ? ? ? ? //如果數組中的元素比maxNum大,則獲取數組中的值
maxNum = arr[i];
return maxNum;
int main(void)
? ? //定義int數組并初始化
int numArr[3] = {3, 8, 6};
? ??
? ? //自動調用int getMax(int a, int b)
cout << getMax(numArr[0], numArr[2]) << endl;
? ? //自動調用返回數組中最大值的函數返回數組中的最大值
cout << getMax(numArr, 3) << endl;
return 0;
是不是數組的形參沒加*號,導致兩個形參都是int類型跟上邊的getMax重復了
int getMax(int *a,int count)
? ? int tem=a[0];
if(tem<a[i])
tem=a[i];
return tem;
舉報
C++掃清通往面向對象的最后一道障礙,將所有知識點融會貫通
Copyright ? 2025 imooc.com All Rights Reserved | 京ICP備12003892號-11 京公網安備11010802030151號
購課補貼聯系客服咨詢優惠詳情
慕課網APP您的移動學習伙伴
掃描二維碼關注慕課網微信公眾號
2017-10-07
同學這是網站設計的原因,他有提示你用maxNum做變量,所以你用tem做變量雖然編程沒問題,但是網站不是編譯器,與事先答案比較發現變量名不一樣就判斷你錯誤。而且你也要將函數定義中的*a改成*arr,這不是你的代碼有問題,是因為網站不是編譯器只會和答案比較找錯的原因。(附上我的代碼供你參考,我這個它就認為正確通過了)
#include <iostream>
using namespace std;
/**
? *函數功能:返回a和b的最大值
? *a和b是兩個整數
? */
int getMax(int a, int b)
{
? ? return a > b ? a : b;
}
/**
? * 函數功能:返回數組中的最大值
? * arr:整型數組
? * count:數組長度
? * 該函數是對上面函數的重載
? */
int getMax(int *arr, int count)
{
? ? //定義一個變量并獲取數組的第一個元素
? ? int maxNum = arr[0];
for(int i = 1; i < count; i++)
{
? ? ? ? //比較變量與下一個元素的大小
if(arr[i] > maxNum)
{
? ? ? ? ? ? //如果數組中的元素比maxNum大,則獲取數組中的值
maxNum = arr[i];
}
}
return maxNum;
}
int main(void)
{
? ? //定義int數組并初始化
int numArr[3] = {3, 8, 6};
? ??
? ? //自動調用int getMax(int a, int b)
cout << getMax(numArr[0], numArr[2]) << endl;
? ??
? ? //自動調用返回數組中最大值的函數返回數組中的最大值
cout << getMax(numArr, 3) << endl;
return 0;
}
2017-10-07
是不是數組的形參沒加*號,導致兩個形參都是int類型跟上邊的getMax重復了
int getMax(int *a,int count)
{
? ? //定義一個變量并獲取數組的第一個元素
? ? int tem=a[0];
for(int i = 1; i < count; i++)
{
? ? ? ? //比較變量與下一個元素的大小
if(tem<a[i])
{
? ? ? ? ? ? //如果數組中的元素比maxNum大,則獲取數組中的值
tem=a[i];
}
}
return tem;
}