Java/Language Basics/Modulus
Версия от 18:01, 31 мая 2010; (обсуждение)
Detect even/odd number with the modulus operator.
public class Main {
public static void main(String[] argv) {
int x = 5;
if (x % 2 == 0) {
System.out.println("even");
}
if (x % 2 != 0) {
System.out.println("odd");
}
// ... or binary AND operator...
if ((x & 1) == 0) {
System.out.println("even");
}
if ((x & 1) != 0) {
System.out.println("odd");
}
}
}
Modulus Operator Example
public class Main {
public static void main(String[] args) {
int i = 5;
double d = 2;
System.out.println("i mod 10 = " + i % 10);
System.out.println("d mod 10 = " + d % 10);
}
}
/*
i mod 10 = 5
d mod 10 = 2.0
*/