首页 > 图灵资讯 > 技术篇>正文
Modulo或Java的剩余时间
2025-02-18 20:54:42
Java中的模运算符(余数)
模算符(%)返回两个数相除后的余数。 举例来说,对于整数 a 和 b,a % b 计算 a 除以 b 的余数。
要点:
- 若被除数小于除数,则模运算的结果是被除数本身。
语法:
立即学习“Java免费学习笔记(深入);
a % b // A是除数,B是除数,B是除数
计算商和余数:
int quotient = a / b; // 商 int remainder = a % b; // 余数
示例程序1:提取个位数
该程序演示了如何使用模操作符依次提取整数的个位数:
public class RemainderExample { public static void main(String[] args) { int number = 6547; while (number > 0) { System.out.println(number % 10); // 输出个位数 number /= 10; // 去掉个位数 } } }
输出:
7 4 5 6
示例程序2:计算商和余数
计算一个整数除以另一个整数的商和余数:
public class QuotientRemainder { public static void main(String[] args) { int number = 6547; int remainder; int quotient; while (number > 0) { remainder = number % 10; System.out.println("余数: " + remainder); quotient = number / 10; System.out.println("商: " + quotient); number = quotient; } } }
输出:
余数: 7 商: 654 余数: 4 商: 65 余数: 5 商: 6 余数: 6 商: 0
参考链接:
- GeeksforGeeks: Java中的模运算符
- GeeksforGeeks: Java中商和余数的程序
以上是Modulo或Java剩余时间的详细内容。请关注图灵教育的其他相关文章!
