Java 检查数字是否能被5整除
在数学中,数字是否能被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(%)运算符来检查可被整除性规则的条件。一旦数字可被整除,则打印结果,否则不打印。我们可以通过参考这个程序来了解其他数字的可被整除性规则。