C #에서 양수를 음수로 변환
다음과 같이 음수를 양수로 변환 할 수 있습니다.
int myInt = System.Math.Abs(-5);
양수를 음수로 만드는 동등한 방법이 있습니까?
어때요?
myInt = myInt * -1
int myNegInt = System.Math.Abs(myNumber) * (-1);
int negInt = -System.Math.Abs(myInt)
다른 것을 부정적으로 만드는 것과 같은 방법으로, 그 앞에 부정적인 부호를 넣으십시오.
var positive = 6;
var negative = -positive;
응답 한 모든 사람에게 메모
- Math.Abs(myInteger)
또는
0 - Math.Abs(myInteger)
또는
Math.Abs(myInteger) * -1
음수를 음수로 유지하고 양수를 음수로 바꾸는 방법으로
이 접근법에는 하나의 결함이 있습니다. 모든 정수에서 작동하지는 않습니다. Int32
유형 의 범위는 "-2 31 "~ "2 31-1 "입니다. "음수"가 하나 더 있음을 의미합니다. 따라서 Math.Abs(int.MinValue)
던진다 OverflowException
.
올바른 방법은 조건문을 사용하는 것입니다.
int neg = n < 0 ? n : -n;
이 접근 방식은 "모든"정수에 적용됩니다.
쉬운 방법 :
myInt *= -1;
int negInt = 0 - myInt;
또는 부정적인 것으로 보장됩니다.
int negInt = -System.Math.Abs(someInt);
정수 부호를 바꾸려면 부호 연산자를 사용하면됩니다.
myInt = -myInt;
원래 값이 음수인지 여부에 관계없이 음수로 만들려면 먼저 Abs 방법을 사용하십시오.
myInt = -Math.Abs(myInt);
더 재미있게 :
int myInt = Math.Min(hisInt, -hisInt);
int myInt = -(int)Math.Sqrt(Math.Pow(Math.Sin(1), 2) + Math.Pow(Math.Cos(-1), 2))
* Math.Abs(hisInt);
편집 : 이것은 양의 입력에 대해 잘못입니다 ...- x (2s-Complement value)의 나머지 비트가 + x의 값의 '반대'가 아니라는 것을 잊어 버렸습니다. 따라서 단순히 부호 비트를 변경하면 양수에는 작동하지 않습니다.
나는 이것을 목적으로 여기에 남겨 둘 것입니다 ...
또는 까다로운 방법 (제 생각에는) ...
int y = x | ~ int.MaxValue;
cause int.MaxValue is 0111 1111 1111 1111 1111 1111 1111 1111
그래서
~int.MaxValue is 1000 0000 0000 0000 0000 0000 0000 0000
따라서 int32 Or'ed를 사용하면 부호 비트에 1을 넣고 (음수) 다른 모든 비트를 동일하게 유지합니다 ...
편집 : 실제로 1000 0000 0000 0000 0000 0000 0000 0000은 실제로 최소값이므로 다음과 같이 작동합니다.
int y = x | int.MinValue; // or, to do it to itself,
x |= int.MinValue;
재미로:
int negativeInt = int.Parse(String.Format("{0}{1}",
"-", positiveInt.ToString()));
Update: the beauty of this approach is that you can easily refactor it into an exception generator:
int negativeInt = int.Parse(String.Format("{0}{1}",
"thisisthedumbestquestioninstackoverflowhistory", positiveInt.ToString()));
Even though I'm way late to the party here, I'm going to chime in with some useful tricks from my hardware days. All of these assume 2's compliment representation for signed numbers.
int negate = ~i+1;
int positiveMagnitude = (i ^ (i>>31)) - (i>>31);
int negativeMagnitude = (i>>31) - (i ^ (i>>31));
I use myInt = -myInt;
So simple and easy
If you want to have only positive
myInt = myInt>0 ? myInt : -myInt;
long negativeNumber = (long)positiveInt - (long)(int.MaxValue + 1);
Nobody said it had to be any particular negative number.
Maybe this?
int n;
.... some coding....
n = n<=0? n:0-n;
int myInt = - System.Math.Abs(-5);
Multiply it by -1.
Converting a number from positive to negative, or negative to positive:
public static decimal Reverse(this decimal source)
{
return source * decimal.MinusOne;
}
Just something that I want to share.
public decimal NumberReevaluate(decimal number, bool isPositive)
{
var tempNumber = System.Math.Abs(number);
return isPositive ? tempNumber : -tempNumber;
}
As previously mentioned, just multiplying by -1 is not cool, as int.MinValue * -1 == int.MinValue
It really depends on your application, but for mine (Inverting Joystick axes) I want to ensure that all extremes are still reachable, and maintain as much fidelity as possible.
To this end, I map Max <--> Min and everything in-between gets a * -1
Using this technique, -32767 is unreachable when inverting.
private static int Invert(int value) { if (value == int.MaxValue) return int.MinValue; if (value == int.MinValue) return int.MaxValue; return value * -1; }
Use binary and to remove the last bit which is responsible for negative sign.
Or use binary or to add sign to a datatype.
This soln may sound absurd and incomplete but I can guarantee this is the fastest method.
If you don't experiment with what I have posted this post may look crap :D
Eg for int:
Int is 32 bit datatype so the last bit (32th one) determines the sign.
And with a value which has 0 in the 32 place and rest 1. It will convert negative no to +ve.
For just the opposite or with a value with 1 in 32th place and rest 0.
X=*-1
may not work on all compilers... since it reads a 'multiply' 'SUBTRACT' 1 instead of NEGATIVE The better alt is X=(0-X)
, [WHICH IS DIFF FROM X-=X
]
참고URL : https://stackoverflow.com/questions/1348080/convert-a-positive-number-to-negative-in-c-sharp
'IT' 카테고리의 다른 글
Amazon Recommendation 기능은 어떻게 작동합니까? (0) | 2020.06.19 |
---|---|
JavaScript에서 define ([, function])이란 무엇입니까? (0) | 2020.06.19 |
GHC-mod는 타입에 전체 이름을 사용해야합니까? (0) | 2020.06.18 |
PHP MySQL 구글 차트 JSON-완전한 예제 (0) | 2020.06.18 |
MVVM을 사용하여 wpf의 대화 상자에 대한 좋은 습관 또는 나쁜 습관? (0) | 2020.06.18 |