[英]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);
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.