How to round up integer division and have int result in Java?(如何在 Java 中舍入整数除法并获得 int 结果?)
问题描述
我刚刚写了一个小方法来计算手机短信的页数.我没有选择使用 Math.ceil 进行四舍五入,老实说,它看起来很丑.
I just wrote a tiny method to count the number of pages for cell phone SMS. I didn't have the option to round up using Math.ceil, and honestly it seems to be very ugly.
这是我的代码:
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.有什么想法吗?
I don't really like this piece of code and I'm looking for a more elegant way of doing this. With this, I'm expecting 3 and not 3.0000000. Any ideas?
推荐答案
你可以使用整数除法来四舍五入
To round up an integer division you can use
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);
}
或者如果两个数字都是正数
or if both numbers are positive
public static long roundUp(long num, long divisor) {
return (num + divisor - 1) / divisor;
}
这篇关于如何在 Java 中舍入整数除法并获得 int 结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Java 中舍入整数除法并获得 int 结果?
基础教程推荐
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
