Java中的模运算符(余数)
模运算符(%)返回两个数相除后的余数。 例如,对于整数 a 和 b,a % b 计算 a 除以 b 的余数。
要点:
语法:
立即学习“Java免费学习笔记(深入)”;
a % b // a是被除数,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
参考链接:
以上就是Modulo或Java的剩余时间的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号