在 C# 中将正数转换为负数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1348080/
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
Convert a positive number to negative in C#
提问by
You can convert a negative number to positive like this:
您可以像这样将负数转换为正数:
int myInt = System.Math.Abs(-5);
Is there an equivalent method to make a positive number negative?
是否有等效的方法使正数变为负数?
采纳答案by bryanbcook
How about
怎么样
myInt = myInt * -1
回答by TJ L
int negInt = 0 - myInt;
Or guaranteed to be negative.
或者保证为负。
int negInt = -System.Math.Abs(someInt);
回答by Jim W
int myNegInt = System.Math.Abs(myNumber) * (-1);
回答by driis
The easy way:
简单的方法:
myInt *= -1;
回答by Warren Pena
Multiply it by -1.
乘以-1。
回答by JDunkerley
int negInt = -System.Math.Abs(myInt)
回答by Joe White
The same way you make anything else negative: put a negative sign in front of it.
用同样的方法让其他任何东西变成负数:在它前面放一个负号。
var positive = 6;
var negative = -positive;
回答by impomatic
int myInt = - System.Math.Abs(-5);
回答by Charles Bretana
EDIT: This is wrong for positive inputs... I made mistake of forgetting that the rest of the bits in -x (2s-Complement value) are the 'opposite' of their value in +x, not the same. SO simply changing the sign bit will NOT work for positive numbers.
编辑:这对于正输入是错误的......我错误地忘记了 -x 中的其余位(2s-补码值)是它们在 +x 中的值的“相反”,不相同。所以简单地改变符号位对正数不起作用。
I'll leave this here for in for purposes...
出于目的,我将把它留在这里...
Or the tricky way ( I think )...
或棘手的方式(我认为)...
int y = x | ~int.MaxValue;
整数 y = x | ~int.MaxValue;
cause int.MaxValue is 0111 1111 1111 1111 1111 1111 1111 1111
so
所以
~int.MaxValue is 1000 0000 0000 0000 0000 0000 0000 0000
and therefore any int32 Or'ed with that will put a 1 in the sign bit, (making it negative), and leave all the other bits the same...
因此,任何 int32 Or'ed 都会在符号位中放置一个 1(使其为负),并使所有其他位保持不变......
EDIT: actually, Since the 1000 0000 0000 0000 0000 0000 0000 0000 is actually the Minvalue, this should also work:
编辑:实际上,由于 1000 0000 0000 0000 0000 0000 0000 0000 实际上是 Minvalue,这也应该有效:
int y = x | int.MinValue; // or, to do it to itself,
x |= int.MinValue;
回答by Guffa
To switch the sign of an integer, you just use the sign operator:
要切换整数的符号,只需使用符号运算符:
myInt = -myInt;
To make it negative regardless if the original value is negative or not, you first use the Abs method:
无论原始值是否为负,要使其为负,您首先使用 Abs 方法:
myInt = -Math.Abs(myInt);