首頁 >後端開發 >C++ >如何在 C# 未排序數組中找到最大值及其索引?

如何在 C# 未排序數組中找到最大值及其索引?

Susan Sarandon
Susan Sarandon原創
2024-12-27 07:09:14309瀏覽

How to Find the Maximum Value and Its Index in a C# Unsorted Array?

在C# 中尋找未排序數值數組中的最大值和索引

確定未排序數組中的最大值及其索引數字數組,例如int[] anArray = { 1, 5, 2, 7 },您可以使用以下內容方法:

方法:

  1. 利用System.Linq 命名空間中的Max() 方法來識別數組中的最高值。
  2. 使用 ToList() 將陣列轉換為清單以存取其索引功能。
  3. 使用轉換後的清單上的 IndexOf() 來決定最大值的索引。

代碼:

using System.Linq;

int[] anArray = { 1, 5, 2, 7 };

// Find the maximum value
int maxValue = anArray.Max();

// Find the index of the maximum value
int maxIndex = anArray.ToList().IndexOf(maxValue);

// Display the results
Console.WriteLine($"Maximum Value: {maxValue}");
Console.WriteLine($"Index of Maximum Value: {maxIndex}");

輸出:

Maximum Value: 7
Index of Maximum Value: 3

以上是如何在 C# 未排序數組中找到最大值及其索引?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn