development

음수를 양수로 만드십시오

big-blog 2020. 6. 26. 07:47
반응형

음수를 양수로 만드십시오


숫자 세트를 합산하는 Java 메소드가 있습니다. 그러나 음수를 양수로 취급하고 싶습니다. 따라서 (1) + (2) + (1) + (-1)은 5와 같아야합니다.

나는이 작업을 수행하는 매우 쉬운 방법이 있다고 확신합니다. 어떻게하는지 모르겠습니다.


Math.abs를 호출하십시오 . 예를 들면 다음과 같습니다.

int x = Math.abs(-5);

로 설정 x됩니다 5.


설명하는 개념을 "절대 값"이라고하며 Java에는 Math.abs 라는 함수 가 있습니다. 또는 함수 호출을 피하고 직접 할 수 있습니다.

number = (number < 0 ? -number : number);

또는

if (number < 0)
    number = -number;

당신은 절대 가치를 찾고 있습니다, 친구. Math.abs(-5)5를 반환합니다 ...


abs기능을 사용하십시오 :

int sum=0;
for(Integer i : container)
  sum+=Math.abs(i);

이 코드는 양수로 호출 해도 안전 하지 않습니다 .

int x = -20
int y = x + (2*(-1*x));
// Therefore y = -20 + (40) = 20

절대 값에 대해 묻고 있습니까?

Math.abs (...)는 아마도 원하는 함수입니다.


각 번호를로 묶으려고 Math.abs()합니다. 예 :

System.out.println(Math.abs(-1));

"1"을 인쇄합니다.

Math.-part를 작성하지 않으려면 Math 유틸리티를 정적으로 포함시킬 수 있습니다. 그냥 써

import static java.lang.Math.abs;

수입품과 함께, 당신은 abs()서면으로 -function을 참조 할 수 있습니다

System.out.println(abs(-1));

이것을 시도하십시오 (단일 연산자이기 때문에 x 앞의 음수가 유효합니다. 자세한 내용은 여기를 참조 하십시오 ).

int answer = -x;

이를 통해 양수를 음수로, 음수를 양수로 바꿀 수 있습니다.


그러나 음수를 양수로 만들려면 다음을 시도하십시오.

int answer = Math.abs(x);

또는 어떤 이유로 abs () 메소드를 사용하지 않으려면 다음을 시도하십시오.

int answer = Math.sqrt(Math.pow(x, 2));

그것이 도움이되기를 바랍니다! 행운을 빕니다!


가장 쉬운 방법은 자세한 방법은 Math.abs () 호출에서 각 숫자를 래핑하는 것입니다.

Math.abs(1) + Math.abs(2) + Math.abs(1) + Math.abs(-1)

코드 구성 방식을 반영하기 위해 논리 변경 사항이 포함됩니다. 아마도 장황하지만, 그것은 당신이 원하는 것을합니다.


손실 또는 부재 개념이없는 값 (음수 값)을 나타내야하는 경우이를 "절대 값"이라고합니다.


절대 값을 얻는 논리는 매우 간단 "If it's positive, maintain it. If it's negative, negate it"합니다.


이것이 의미하는 것은 논리와 코드가 다음과 같이 작동해야한다는 것입니다.

//If value is negative...
if ( value < 0 ) {
  //...negate it (make it a negative negative-value, thus a positive value).
  value = negate(value);
}

값을 부정 할 수있는 두 가지 방법이 있습니다.

  1. 글쎄, 그 가치를 부정하면 : value = (-value);
  2. "100 % 음수"또는 "-1"을 곱하여 : value = value * (-1);

둘 다 실제로 같은 동전의 양면입니다. value = (-value);실제로는 실제로 기억하지 않는다는 value = 1 * (-value);입니다.


Well, as for how you actually do it in Java, it's very simple, because Java already provides a function for that, in the Math class: value = Math.abs(value);

Yes, doing it without Math.abs() is just a line of code with very simple math, but why make your code look ugly? Just use Java's provided Math.abs() function! They provide it for a reason!

If you absolutely need to skip the function, you can use value = (value < 0) ? (-value) : value;, which is simply a more compact version of the code I mentioned in the logic (3rd) section, using the Ternary operator (? :).


Additionally, there might be situations where you want to always represent loss or absence within a function that might receive both positive and negative values.

Instead of doing some complicated check, you can simply get the absolute value, and negate it: negativeValue = (-Math.abs(value));


With that in mind, and considering a case with a sum of multiple numbers such as yours, it would be a nice idea to implement a function:

int getSumOfAllAbsolutes(int[] values){
  int total = 0;
  for(int i=0; i<values.lenght; i++){
    total += Math.abs(values[i]);
  }
  return total;
}

Depending on the probability you might need related code again, it might also be a good idea to add them to your own "utils" library, splitting such functions into their core components first, and maintaining the final function simply as a nest of calls to the core components' now-split functions:

int[] makeAllAbsolute(int[] values){
  //@TIP: You can also make a reference-based version of this function, so that allocating 'absolutes[]' is not needed, thus optimizing.
  int[] absolutes = values.clone();
  for(int i=0; i<values.lenght; i++){
    absolutes[i] = Math.abs(values[i]);
  }
  return absolutes;
}

int getSumOfAllValues(int[] values){
  int total = 0;
  for(int i=0; i<values.lenght; i++){
    total += values[i];
  }
return total;
}

int getSumOfAllAbsolutes(int[] values){
  return getSumOfAllValues(makeAllAbsolute(values));
}

Why don't you multiply that number with -1?

Like This:

//Given x as the number, if x is less than 0, return 0 - x, otherwise return x:
return (x <= 0.0F) ? 0.0F - x : x;

I would recommend the following solutions:

without lib fun:

    value = (value*value)/value

with lib fun:

   value = Math.abs(value);

If you're interested in the mechanics of two's complement, here's the absolutely inefficient, but illustrative low-level way this is made:

private static int makeAbsolute(int number){
     if(number >=0){
        return number;
     } else{
        return (~number)+1;
     }
}

String s = "-1139627840";
BigInteger bg1 = new BigInteger(s);
System.out.println(bg1.abs());

Alternatively:

int i = -123;
System.out.println(Math.abs(i));

Library function Math.abs() can be used.
Math.abs() returns the absolute value of the argument

  • if the argument is negative, it returns the negation of the argument.
  • if the argument is positive, it returns the number as it is.

e.g:

  1. int x=-5;
    System.out.println(Math.abs(x));

Output: 5

  1. int y=6;
    System.out.println(Math.abs(y));

Output: 6


I needed the absolute value of a long , and looked deeply into Math.abs and found that if my argument is less than LONG.MIN_VAL which is -9223372036854775808l, then the abs function would not return an absolute value but only the minimum value. Inthis case if your code is using this abs value further then there might be an issue.


dont do this

number = (number < 0 ? -number : number);

or

if (number < 0) number = -number;

this will be an bug when you run find bug on your code it will report it as RV_NEGATING_RESULT_OF

참고URL : https://stackoverflow.com/questions/493494/make-a-negative-number-positive

반응형