C 求陣列最大值或最大值位置索引

2022-05-05 14:57:09 字數 1739 閱讀 8775

常見求最大值,是數值型陣列,這個通常遍歷陣列方式,或陣列排序即可完成。但對於字串或日期等非數值型別不能處理。下面給出泛型陣列的最大值或最大值位置索引的自定義函式。

陣列最大值的位置索引

//

傳入乙個陣列,求出乙個陣列的最大值的位置

public

static

int maxindex(t arr) where t : icomparable

}return

i_pos;

}

陣列最大值

//

傳入乙個陣列,求出乙個陣列的最大值

public

static t maxvalue(t arr) where t : icomparable

}return

value;

}

測試例如下:

int arr = ;

console.writeline(

"index=, value=, type=

",maxindex(arr),maxvalue(arr), maxvalue(arr).gettype());

datetime days = ;//

, datetime.parse("2020-01-11") };

console.writeline("

index=, value=, type=

", maxindex(days), maxvalue(days), maxvalue(days).gettype());

string name = ;

console.writeline(

"index=, value=, type=

", maxindex(name), maxvalue(name), maxvalue(name).gettype());

同樣地,你也可以寫出乙個求最小值的函式。

完整vs示例如下:

using

system;

namespace

}return

i_pos;

}//傳入乙個陣列,求出乙個陣列的最大值

public

static t maxvalue(t arr) where t : icomparable

}return

value;

}static

void main(string

args)

;console.writeline(

"index=, value=, type=

",maxindex(arr),maxvalue(arr), maxvalue(arr).gettype());

datetime days = ;//

, datetime.parse("2020-01-11") };

console.writeline("

index=, value=, type=

", maxindex(days), maxvalue(days), maxvalue(days).gettype());

string name = ;

console.writeline(

"index=, value=, type=

", maxindex(name), maxvalue(name), maxvalue(name).gettype());

console.readkey();}}

}

遞迴求陣列最大值

遞迴求陣列最大值 使用遞迴當方式求陣列中最大的值 public class diguigetmax int mid l r 2 int leftmax getmax a,0,mid int rightmax getmax a,mid 1,r return math.max leftmax,right...

求陣列中最大值

所有c語言 都是在loadrunner中執行 action 定義乙個int陣列 int len 記錄陣列元素個數 int max 所求的最大值 int i 迴圈變數 loadrunnerg中,不能在for迴圈中定義變數 len sizeof a sizeof int 陣列元素個數 陣列所佔字元數 陣...

類模板 求陣列最大值

問題及 all right reserved,檔名 test.cpp 完成日期 2015年6月22日 版本號 v1.0 問題描述 類模板 求陣列最大值 輸入描述 程式輸出 include include using namespace std template class array max 宣告類...