java 除尽 取余
时间: 2023-11-18 16:56:44 浏览: 124
Java中的除法运算符是“/”,取余运算符是“%”。当除数为0时,整数除法会抛出一个算术异常ArithmeticException。而整数取余运算中,除数为0也会抛出一个ArithmeticException异常。当除数不为0时,如果被除数可以被除尽,即余数为0,则除法运算的结果就是商;如果被除数不能被除尽,则除法运算的结果就是商的整数部分。而取余运算的结果就是被除数除以除数所得的余数。例如,A%10(A>=10)的结果,要么是除尽了,余数为0,要么,余数为最后一位;B%100(B>=100)的结果,要么是除尽了,余数为0,要么,余数为最后两位。
相关问题
两个数相除,能除尽取整,不能除尽保留2位小数,java bigdecimal
使用Java BigDecimal可以实现两个数相除,能除尽取整,不能除尽保留2位小数的功能,具体实现如下:
```
import java.math.BigDecimal;
public class BigDecimalDemo {
public static void main(String[] args) {
BigDecimal num1 = new BigDecimal("10");
BigDecimal num2 = new BigDecimal("3");
BigDecimal result = num1.divide(num2, 2, BigDecimal.ROUND_HALF_UP);
System.out.println(result);
}
}
```
在上述代码中,先创建两个BigDecimal类型的数num1和num2,然后使用divide方法进行相除操作,其中第一个参数为被除数,第二个参数为除数,第三个参数为保留小数位数和舍入规则。在本例中,保留2位小数,并且采用四舍五入的舍入规则,最后将结果输出即可。
需要注意的是,如果除数为0,会抛出ArithmeticException异常,需要进行异常处理。
Android 取余
在 Android 中,取余操作使用 % 符号实现。取余操作通常被称为模运算,计算的结果为 a 对 b 取余的余数,其中 a 和 b 可以是整数或浮点数。取余操作符用于返回两个数相除后的余数。例如,5%2=1,因为2可以除尽2次,剩下1。
需要注意的是,在进行取余运算时,如果被除数是负数,则结果的符号与除数一致。例如,-5%3 的结果为-2。同时,如果除数为0,则会引发除以零异常(ArithmeticException)。
阅读全文
相关推荐
















