C 尋找陣列最大值和最小值

2021-08-28 04:00:51 字數 1216 閱讀 5441

c++裡面有好多自帶函式可以直接用,比如尋找陣列中的最大最小值其實是有函式的,如下

#include using namespace std;

#include int main()

cout << (*min_element(p, p + n))<<' '<< (*max_element(p, p + n)) << endl;

return 0;

}

需要用標頭檔案,*min_element(p, p + n)就是在p~p+n範圍內的最小的數,max類同。

另外還有很多常用的函式都有自帶的,對於像我一樣程式設計經驗不是很多的小白節省了不少時間,

比如求和函式,要求乙個陣列中的元素之和,可以用函式 accumulate(),需要包括標頭檔案

#include using namespace std;

#include int main()

cout << accumulate(p, p + n, 0) << endl;

return 0;

}

另外比較笨的方法是自己寫判斷函式

/*

知識點:bool 型別 命名空間 輸入輸出

題目要求:使用函式找出乙個整型陣列中的最大值或最小值

*/

#include#includeusing namespace std;

int getmaxormin(int *arr,int count,bool ismax)

} } return temp;

}int main(void);

bool ismax=false;

cin>>ismax;//從鍵盤接收

cout《使用命名空間

/*知識點:bool 型別 命名空間 輸入輸出

題目要求:使用函式找出乙個整型陣列中的最大值或最小值

*/

#include#includeusing namespace std;

namespace compa

} } return temp; }}

int main(void);

bool ismax=false;

cin>>ismax;//從鍵盤接收

cout

return 0;

}

尋找陣列中最大值和最小值

最簡單的方法就是n中的每個數分別和max,min比較,看似2n次比較,其實大於max的就不必和min比較,小於min的也不必和max比較,因此比較的次數不足2n次,程式如下 bool maxmin std vectorarray,t max,t min max array 0 min array 0...

尋找陣列中的最大值和最小值

問題描述 給出乙個陣列,包含n個整數,那麼需要比較多少次找到最大值和最小值 注意 要想得到最大值和最小值,遍歷一遍陣列是不可避免的。我們能減少的就是減少比較次數來提高效率 方法一 遍歷一遍陣列,同時得到最大值和最小值 具體是,定義乙個max 和 min,每遍歷乙個數,就分別和max 和 min比較一...

尋找陣列中的最大值和最小值

如何尋找陣列中的最大值和最小值 維持兩個變數min,max,每次比較相鄰的兩個數,較大者與max比較,較小者與min比較,通過比較找出最值。比較次數為1.5n次。public class maxmin public static void main string args int arr1 null...