Tôi vừa viết một phương pháp nhỏ để đếm số trang cho SMS điện thoại di động. Tôi không có tùy chọn để làm tròn lên bằng cách sử dụng Math.ceil
, và thực sự nó có vẻ rất xấu xí.Làm thế nào để làm tròn phân chia số nguyên và có kết quả int trong Java?
Đây là mã của tôi:
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);
}
}
}
tôi không thực sự thích đoạn mã này và tôi đang tìm kiếm một cách thanh lịch hơn để làm điều này. Với điều này, tôi mong đợi 3 và không 3.0000000. Bất kỳ ý tưởng?
có thể trùng lặp với [Làm thế nào để làm tròn kết quả của bộ phận số nguyên] (http: // stackoverflow.com/questions/17944/how-to-round-up-the-kết quả-of-số nguyên-phân chia) – Raedwald