c# – 编写程序以查找数组中Max项的索引
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 编写程序以查找数组中Max项的索引,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1835字,纯文字阅读大概需要3分钟。
内容图文
Write a console app in C# to find an index i in an array that is the maximum number in the array.
If the maximum element in the array occurs several times, you need to display the minimum index.
If the array is empty, output -1.
请告诉我我的代码有什么问题?
如果我输入数组a = {1,2,46,14,64,64} ;,例如,它返回0,而它应该返回4.
public static void Main()
{
double[] a = { 1, 9, 9, 8, 9, 2, 2 };
Console.WriteLine(MaxIndex(a));
}
public static double MaxIndex(double[] array)
{
var max = double.MinValue;
int maxInd = 0, maxCount = 0;
int minIndex = 0;
var min = double.MaxValue;
for (var i = 0; i < array.Length; i++)
{
if (min > array[i])
{
min = array[i];
minIndex = i;
}
if (max == array[i])
maxCount++;
if (max < array[i])
{
maxCount = 1;
max = array[i];
maxInd = i;
}
}
if (array.Length == 0)
return -1;
if (maxCount > 1)
return minIndex;
return maxInd;
}
解决方法:
您的计算是正确的,但是返回错误的变量minIndex而不是maxIndex.不要在方法中做超过必要的事情.这也计算了最小指数和计数出现频率,然后它对结果没有任何作用.这是一个紧凑版本:
public static int MaxIndex(double[] array)
{
var max = double.MinValue;
int maxInd = -1;
for (int i = 0; i < array.Length; i++)
{
if (max < array[i])
{
max = array[i];
maxInd = i;
}
}
return maxInd;
}
它还设置maxInd = -1,这是您要求的一部分.由于MatthewWatson对于在数组中重复double.MinValue有异议,这里是一个优化版本:
public static int MaxIndex(double[] array)
{
if(array.Length == 0)
return -1;
else if (array.Length == 1)
return 0;
double max = array[0];
int maxInd = 0;
for (int i = 1; i < array.Length; i++)
{
if (max < array[i])
{
max = array[i];
maxInd = i;
}
}
return maxInd;
}
如果代码可读性/可维护性更重要并且您不需要花费更多或更少的时间,则可以使用LINQ(仅枚举一次的版本):
int minIndexOfMaxVal = a.Select((num, index) => new {num, index})
.OrderByDescending(x => x.num)
.Select(x => x.index)
.DefaultIfEmpty(-1)
.First();
这适用于各种序列和类型,不仅适用于数组和双精度数.
内容总结
以上是互联网集市为您收集整理的c# – 编写程序以查找数组中Max项的索引全部内容,希望文章能够帮你解决c# – 编写程序以查找数组中Max项的索引所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。