我只是写了一个小方法来计算手机短信的页数。我没有选择使用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而不是3.0000000。有什么想法吗?
答案 0 :(得分:136)
使用Math.ceil()
并将结果转换为int:
示例:
(int) Math.ceil((double)divident / divisor);
答案 1 :(得分:99)
要整数整数除法,您可以使用
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;
}
答案 2 :(得分:34)
另一个不太复杂的单线:
private int countNumberOfPages(int numberOfObjects, int pageSize) {
return numberOfObjects / pageSize + (numberOfObjects % pageSize == 0 ? 0 : 1);
}
可以使用long而不是int;只需更改参数类型和返回类型。
答案 3 :(得分:15)
Google的Guava图书馆handles this in the IntMath class:
IntMath.divide(numerator, divisor, RoundingMode.CEILING);
与此处的许多答案不同,它处理负数。当尝试除以零时,它也会抛出一个适当的异常。
答案 4 :(得分:10)
(message.length() + 152) / 153
这将给出一个“向上舍入”的整数。
答案 5 :(得分:7)
long numberOfPages = new BigDecimal(resultsSize).divide(new BigDecimal(pageSize), RoundingMode.UP).longValue();
答案 6 :(得分:0)
如果你想计算除以b的四舍五入,你可以使用(a +( - a%b))/ b
答案 7 :(得分:-1)
扩展彼得的解决方案,这是我发现的对我来说总是朝着正向无限的方向发展:
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);
}
}
答案 8 :(得分:-2)
这可能会有帮助, 将剩余部分减去长度并使其成为可分数,然后将其除以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