首页 > 后端开发 > C++ > 如何在 C# 未排序数组中查找最大值及其索引?

如何在 C# 未排序数组中查找最大值及其索引?

Susan Sarandon
发布: 2024-12-27 07:09:14
原创
306 人浏览过

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中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板