Java 程序检查数字是否能被 5 整除
javaobject oriented programmingprogramming更新于 2024/4/19 11:56:17
在数学中,5 的整除规则规定,如果数字以 0 或 5 结尾,那么它将能被 5 整除。还有另一种方法可以识别 5 的整除规则,如果余数为 0,则返回数字能被 5 整除。在编程中,当涉及到整除性时,通常使用 mod(%) 运算符。
让我们举个例子。
给定数字为 525,数字以 5 结尾,可以被 5 整除。
给定数字为 7050,数字以 0 结尾,可以被 5 整除。
给定数字为 678,该数字不以 0 和 5 结尾,不能被 5 整除。
在本文中,我们将解决该数字是否可以被 5 整除。
算法
以下步骤为
我们将使用 java.util.* 包来获取原始数据类型的用户输入。
从主类开始,初始化整数变量以存储输入的整数。
然后使用 mod(%) 运算符将整数变量除以 5。
最后,打印结果。
示例 1
在此程序中,我们将使用 if-else 语句来检查该数字是否可以被 5 整除或不是。
import java.util.*;
public class Check_Divisiblity_of_five {
public static void main(String[] args) {
int number =590;
if (number % 5 == 0)
System.out.println(number+ "\tis the number is divisible by 5");
else
System.out.println(number+ "\tThe number is not divisible by 5");
}
}
输出
590 is the number is divisible by 5
示例 2
在此程序中,我们将获取一个输入变量,并使用"!="运算符在 if 语句的条件中对其进行检查。如果带有 mod(%) 运算符的整数变量不等于 0,则会导致该数字可被 5 整除。
import java.util.*;
public class Check_Divisible_five {
public static void main(String[] args) {
int n=109;
if(n % 5 != 0) {
System.out.println(n+"\t is the number not divisible by 5");
} else {
System.out.println(n+"\t is the number divisible by 5");
}
}
}
输出
109 is the number not divisible by 5
示例 3
在此程序中,我们将数字范围设置为 50-100 之间,并检查该数字是否可以被 5 整除。
import java.util.Scanner;
public class Divisible_by_five {
public static void main(String []args) {
for(int n = 50; n <= 100; n++){
if(n % 5 == 0) {
System.out.println("The number is divisible by 5 :\t"+ n);
}
}
}
}
输出
The number is divisible by 5 : 50 The number is divisible by 5 : 55 The number is divisible by 5 : 60 The number is divisible by 5 : 65 The number is divisible by 5 : 70 The number is divisible by 5 : 75 The number is divisible by 5 : 80 The number is divisible by 5 : 85 The number is divisible by 5 : 90 The number is divisible by 5 : 95 The number is divisible by 5 : 100
结论
我们探索了与 5 的整除性相关的所有三个示例。然后使用 mod(%) 运算符检查整除性规则的条件。一旦数字可整除,它就会打印结果,否则不会。我们还可以通过参考此程序了解其他数字的整除性规则。
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

