简体   繁体   English

求最大绝对数

[英]Finding the maximum of absolute numbers

Is there any quick way of turning all the members of an array into absolute and find the max number among them? 有没有一种快速的方法可以将数组的所有成员转换为绝对成员并在其中找到最大数目? For example in this array: 例如在此数组中:

-100 25 43 -100 25 43

The max is 43, but I want to get 100 from my code. 最大值为43,但我想从代码中获得100。 Is there's any simple/fast method that I can use to find max regardless of its sign? 有什么简单/快速的方法可以找到max而不管其符号如何? or do I have to use a for loop to turn all the array members into absolute and then find the max among them? 还是我必须使用for循环将所有数组成员转换为绝对数组,然后在其中找到最大值?

Try this: 尝试这个:

int[] array = {-100, 25, 43};
int max = array.Select(Math.Abs).Max();

This works: 这有效:

var numbers = new[] { -100, 25, 43 };

var absoluteMax = numbers.Select(x => Math.Abs(x)).Max();

I get 100 as requested. 我得到100要求。

Do be careful if one of your numbers is int.MinValue then you get an OverflowException - "Negating the minimum value of a twos complement number is invalid." 如果您的数字之一是int.MinValue ,请务必小心,然后会收到OverflowException “对二进制补码数字的最小值求反无效。”

Well think about it. 好想想。 You have a list of numbers. 您有一个数字列表。 You need to find the (absolute) maximum. 您需要找到(绝对)最大值。 Can you think of a way of finding the maximum without checking all of them? 您能想到一种无需检查所有最大值即可找到最大值的方法吗? If you check the first 2, can you confidently conclude that you found the maximum, without checking the rest of the array? 如果检查前两个,您是否可以自信地得出结论,找到了最大值,而不检查阵列的其余部分? You can't. 你不能 Thus, you need to check every single number. 因此,您需要检查每个数字。

A basic for loop would do. 一个基本的for循环就可以了。 You don't have any better way than looping. 没有比循环更好的方法了。 Sure, you can use LINQ or other API's that hide the loop from you, but fundamentally that's what they do. 当然,您可以使用LINQ或其他API对您隐藏循环,但是从根本上讲,它们就是这样做的。

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

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