vb.net 中的绝对值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1365229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Absolute value in vb.net
提问by Cyclone
How do you get the absolute value of a number in vb.net?
你如何在vb.net中获得一个数字的绝对值?
Is there a function built in? I know I can simply code a function myself, but I want to know if there is one already there first. It seems so simple, I could probably make it in three lines, so I would be surprised if there isnt one....
有内置函数吗?我知道我可以自己简单地编写一个函数,但我想知道是否已经存在第一个函数。看起来很简单,我大概可以写成三行,所以如果没有一行我会感到惊讶......
Thanks!
谢谢!
回答by MusiGenesis
At the risk of being down-voted, you may want to write your own absolute value method, depending on what you're using it for. The following code snippet (sorry it's in C#, but the same principle applies):
冒着被否决的风险,您可能想要编写自己的绝对值方法,具体取决于您使用它的目的。下面的代码片段(对不起,它是在 C# 中,但同样的原则适用):
short i = -32768;
int iAbs = Math.Abs(i);
will happily compile, but when run, the second line will throw an OverflowException with the helpful message "Negating the minimum value of a twos complement number is invalid." In this case, because i is type short, the compiler chooses the overload of Math.Abs that accepts a short and returns a short, and +32768 is not a valid short, so the method throws the exception even if you thought you were anticipating this problem by making iAbs an int.
将愉快地编译,但是当运行时,第二行将抛出一个 OverflowException 并带有有用的消息“否定二进制补码数的最小值是无效的”。在这种情况下,因为 i 是 short 类型,编译器选择了 Math.Abs 的重载,它接受一个 short 并返回一个 short,而 +32768 不是一个有效的 short,所以即使你认为你是预期的,该方法也会抛出异常通过使 iAbs 成为 int 来解决这个问题。
This snippet:
这个片段:
short i = -32768;
int iAbs = Math.Abs((int)i);
will compile and execute without an exception, but it's kind of clunky to code this way. In my opinion, this is a very sneaky error because it's so rarely encountered in the real world (since there's only one value for each type that will generate this exception). I, unfortunately, run into this error whenever I use Math.Abs for normalizing audio data (which is usually a short[] array), so I've gotten in the habit of writing my own wrapper around Math.Abs that handles all of this for me and just returns a double:
将毫无例外地编译和执行,但以这种方式编码有点笨拙。在我看来,这是一个非常狡猾的错误,因为它在现实世界中很少遇到(因为每种类型只有一个值会产生此异常)。不幸的是,每当我使用 Math.Abs 来规范化音频数据(通常是一个 short[] 数组)时,都会遇到这个错误,所以我养成了在 Math.Abs 周围编写自己的包装器来处理所有这对我来说只是返回一个双:
public double AbsThatDoesntSuck(short value)
{
return Math.Abs((double)value);
}
with overloads for whatever other type I need to handle. I kind of understand why Math.Abs was written to behave this way, but it can definitely bite the behinds of the unaware.
对于我需要处理的任何其他类型的重载。我有点理解为什么 Math.Abs 被写成这样,但它绝对可以咬住不知情的人。
回答by Jason Irwin
The function is Math.Abs
函数是 Math.Abs

