简体   繁体   English

如何在数组中找到最大值

[英]How to find maximum value in an array

var max=0.0d;
for(inc=0;inc<array.length;inc++){
if(max<array[inc])
max=array[inc];
}

I want to find out the maximum value of an array.The above code is generally we used to find out maximum value of an array. 我想找出一个数组的最大值,上面的代码通常是我们用来找出一个数组的最大值。

But this code will return 0 if the array contains only negative values. 但是,如果数组仅包含negative则此代码将返回0 Because 0 < negative never become true 因为0 < negative永远不会变为true

How to handle this conditions. 如何处理这种情况。 Please suggest a solution. 请提出解决方案。

You can try like this if you dont want to try any inbuilt functions: 如果您不想尝试任何内置函数,可以尝试这样:

int max = arr[0];
foreach (int value in arr) 
{
  if (value > max) 
  max = value;
}
Console.WriteLine(max);

IDEONE DEMO IDEONE演示

How to handle this conditions. 如何处理这种情况。

You could initialize the max value as the minimum double: 您可以将最大值初始化为最小值double:

var max = double.MinValue;

Alternatively you could use the .Max() LINQ extension method which will shorten your code, make it more readable and handle the case of an array consisting only of negative values: 或者,您可以使用.Max() LINQ扩展方法,该方法将缩短代码,使其更具可读性并处理仅由负值组成的数组的情况:

var max = array.Max();

You can simply use Max() linq extension. 您可以简单地使用Max() linq扩展。

var maxvalue = array.Max();

Working Demo 工作Demo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM