programing

자바에서 정수 나눗셈을 반올림하여 int 결과를 얻는 방법

bestcode 2022. 9. 19. 23:46
반응형

자바에서 정수 나눗셈을 반올림하여 int 결과를 얻는 방법

휴대폰 문자메시지 페이지 수를 세는 아주 작은 방법을 썼을 뿐이에요.Math.ceil그리고 솔직히 굉장히 못생긴 것 같아요.

코드는 다음과 같습니다.

public class Main {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
   String message = "today we stumbled upon a huge performance leak while optimizing a raycasting algorithm. Much to our surprise, the Math.floor() method took almost half of the calculation time: 3 floor operations took the same amount of time as one trilinear interpolation. Since we could not belive that the floor-method could produce such a enourmous overhead, we wrote a small test program that reproduce";

   System.out.printf("COunt is %d ",(int)messagePageCount(message));



}

public static double messagePageCount(String message){
    if(message.trim().isEmpty() || message.trim().length() == 0){
        return 0;
    } else{
        if(message.length() <= 160){
            return 1;
        } else {
            return Math.ceil((double)message.length()/153);
        }
    }
}

나는 이 코드를 별로 좋아하지 않고 좀 더 우아한 방법을 찾고 있다.이것으로 3.0000000이 아니라 3개를 예상하고 있습니다.좋은 생각 있어요?

사용하다Math.ceil()결과를 int: 에 송신합니다.

  • 이것은 abs()를 사용하여 더블을 회피하는 것보다 더 빠릅니다.
  • -0.999는 0으로 반올림되므로 네거티브 작업 시 결과는 정확합니다.

예:

(int) Math.ceil((double)divident / divisor);

사용할 수 있는 정수 나눗셈을 반올림하려면

import static java.lang.Math.abs;

public static long roundUp(long num, long divisor) {
    int sign = (num > 0 ? 1 : -1) * (divisor > 0 ? 1 : -1);
    return sign * (abs(num) + abs(divisor) - 1) / abs(divisor);
}

또는 두 수치가 모두 양수인 경우

public static long roundUp(long num, long divisor) {
    return (num + divisor - 1) / divisor;
}

너무 복잡하지 않은 또 하나의 라인:

private int countNumberOfPages(int numberOfObjects, int pageSize) {
    return numberOfObjects / pageSize + (numberOfObjects % pageSize == 0 ? 0 : 1);
}

int 대신 long을 사용할 수 있습니다. 매개 변수 유형과 반환 유형을 변경하기만 하면 됩니다.

Google의 Guava 라이브러리는 IntMath 클래스에서 다음을 처리합니다.

IntMath.divide(numerator, divisor, RoundingMode.CEILING);

여기의 많은 대답과 달리, 음수를 처리합니다.또한 0으로 나누기를 시도할 때 적절한 예외가 발생합니다.

(message.length() + 152) / 153

그러면 반올림된 정수가 됩니다.

long numberOfPages = new BigDecimal(resultsSize).divide(new BigDecimal(pageSize), RoundingMode.UP).longValue();

a를 b로 반올림하여 계산하려면 (a+(-a%b)/b)를 사용할 수 있습니다.

Peter의 솔루션을 확장하면, 항상 '긍정적인 무한대'를 향해 나아가야 한다는 것을 알 수 있습니다.

public static long divideAndRoundUp(long num, long divisor) {
    if (num == 0 || divisor == 0) { return 0; }

    int sign = (num > 0 ? 1 : -1) * (divisor > 0 ? 1 : -1);

    if (sign > 0) {
        return (num + divisor - 1) / divisor;
    }
    else {
        return (num / divisor);
    }
}

이것은 도움이 될 수 있습니다. 나머지를 다리까지 뺀 후 나누기 가능한 수로 만든 다음 153으로 나눕니다.

int r=message.length()%153;       //Calculate the remainder by %153
return (message.length()-r)/153;  // find the pages by adding the remainder and 
                                  //then divide by 153 

언급URL : https://stackoverflow.com/questions/7446710/how-to-round-up-integer-division-and-have-int-result-in-java

반응형