Операция взятия остатка от деления в Java
Я уже однажды расписывал операции в Java. В этой статье я акцентрирую внимание на операцию взятия остатка от деления, так как её работа отличается в различных языках программирования и иногда порождает недопонимание.
Операция взятия остатка % в Java работает не только с целыми числами, но и с числами с плавающей точкой.
Для целых чисел операция взятия остатка работает по такому принципу, что результат операции будет таким, что будет выполняться равенство:
Это равенство действует даже в том случае, если левый операнд будет наименьшим отрицательным числом для своего типа, а операнд в правой части будет равен -1 (тогда результатом будет 0).
Результатом операции взятия остатка для целых чисел в Java может быть отрицательное число только в том случае, если левый операнд будет отрицательным числом, а также результат может быть положительным только в том случае, если операнд в левой части будет положительным числом.
Если в правой части операции взятия остатка для целочисленных операндов в Java стоит 0, то результатом будет ArithmeticException .
Примеры работы операции взятия остатка для целочисленных операндов (выполнено в JShell):
Как я уже говорил, в Java операция взятия остатка % работает и с числами с плавающей точкой ( float и double ). Согласно спецификации языка Java операция взятия остатка для чисел с плавающей точкой работает не так, как это принято в IEEE 754, но если очень нужно то можно использовать метод Math . IEEEremainder .
В Java операция взятия остатка % работает согласно следующим правилам:
- Если один из операндов равен NaN, то результат операции будет NaN.
- Если результат не NaN, то знаком результата будет знак операнда в левой части.
- Если операнд в левой части Infinity, или операнд в правой части равен нулю, или выполняются оба условия, то результат будет равен операнду в левой части.
- Если операнд в левой части конечен, а операнд в правой части Infinity, то результат будет равен операнду в левой части.
- Если операнд в левой части равен нулю, а операнд в правой части конечен, то результат будет равен операнду в левой части.
- Во всех остальных случаях результат r взятия остатка от операнда n при делении на d определяется по математической формуле r = n — (d × q), где q будет целым числом, которое отрицательно только в случае, если n / d отрицательно, и положительно, если n / d положительно, и его размер максимально возможный, но не превышающий отношение n и d. Пример: 0,5 ÷ 0,3 = 1,6, тогда q будет положительным, так как 1,6 положительно, а наибольший размер, не превышающий 1,6 будет 1, то q = 1, а значит r = 0,5 — (0,3 × 1) = 0,2.
Операция взятия остатка для чисел с плавающей точкой никогда не приводит к возникновению Exception-ов.
Примеры операции взятия остатка для чисел с плавающей точкой:
Оператор деления по модулю
Оператор деления по модулю — оператор mod , обозначается символом % . Этот оператор возвращает остаток от деления первого операнда на второй. Оператор mod » % » в Java работает не только с целыми (такие как: byte/int/short/long ), но и с плавающей точкой (такие как: float/double ) числами\типами. Приведенная ниже программа иллюстрирует работу этого оператора:
package com.l2cccp.work; public class Mod < public static void main(String args[]) < int i = 17; // Целые double d = 17.3; // С плавающей точкой System.out.println("i mod 10 = " + i % 10); System.out.println("d mod 10 lang-java line-numbers"> i mod 10 = 7 d mod 10 = 7.300000000000001
package com.l2cccp.work; public class Mod < public static void main(String args[]) < int[] day= new int[] < 1, 2, 5 >; System.out.println("Вы играете уже " + day[0] + " " + declension(day[0])); System.out.println("Вы играете уже " + day[1] + " " + declension(day[1])); System.out.println("Вы играете уже " + day[2] + " " + declension(day[2])); > public static String declension(int count) < String one = "день"; String two = "дня"; String five = "дней"; if(count >100) count %= 100; if(count > 20) count %= 10; switch(count) < case 1: return one; case 2: case 3: case 4: return two; default: return five; >> >
Вы играете уже 1 день Вы играете уже 2 дня Вы играете уже 5 дней
- Вы играете уже 1 день и 1 час.
- Вы играете уже 2 дня и 4 часа.
- Вы играете уже 5 дней 9 часов.
package com.l2cccp.work; public class Mod < public static void main(String args[]) < int[] day = new int[] < 1, 2, 5 >; int[] hour = new int[] < 1, 4, 9 >; System.out.println("Вы играете уже " + day[0] + " " + declension(day[0], "Days") + " и " + hour[0] + " " + declension(hour[0], "Hour")); System.out.println("Вы играете уже " + day[1] + " " + declension(day[1], "Days") + " и " + hour[1] + " " + declension(hour[1], "Hour")); System.out.println("Вы играете уже " + day[2] + " " + declension(day[2], "Days") + " и " + hour[2] + " " + declension(hour[2], "Hour")); > public static String declension(int count, String type) < String one = ""; String two = ""; String five = ""; if(type.equals("Days")) < one = "день"; two = "дня"; five = "дней"; >else if(type.equals("Hour")) < one = "час"; two = "часа"; five = "часов"; >if(count > 100) count %= 100; if(count > 20) count %= 10; switch(count) < case 1: return one; case 2: case 3: case 4: return two; default: return five; >> >
Вы играете уже 1 день и 1 час Вы играете уже 2 дня и 4 часа Вы играете уже 5 дней и 9 часов
Assignment, Arithmetic, and Unary Operators
One of the most common operators that you'll encounter is the simple assignment operator " = ". You saw this operator in the Bicycle class; it assigns the value on its right to the operand on its left:
int cadence = 0; int speed = 0; int gear = 1;
This operator can also be used on objects to assign object references, as discussed in Creating Objects.
The Arithmetic Operators
The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics. The only symbol that might look new to you is " % ", which divides one operand by another and returns the remainder as its result.
Operator | Description |
---|---|
+ | Additive operator (also used for String concatenation) |
- | Subtraction operator |
* | Multiplication operator |
/ | Division operator |
% | Remainder operator |
The following program, ArithmeticDemo , tests the arithmetic operators.
This program prints the following:
1 + 2 = 3 3 - 1 = 2 2 * 2 = 4 4 / 2 = 2 2 + 8 = 10 10 % 7 = 3
You can also combine the arithmetic operators with the simple assignment operator to create compound assignments. For example, x+=1; and x=x+1; both increment the value of x by 1.
The + operator can also be used for concatenating (joining) two strings together, as shown in the following ConcatDemo program:
By the end of this program, the variable thirdString contains "This is a concatenated string.", which gets printed to standard output.
The Unary Operators
The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean.
Operator | Description |
---|---|
+ | Unary plus operator; indicates positive value (numbers are positive without this, however) |
- | Unary minus operator; negates an expression |
++ | Increment operator; increments a value by 1 |
-- | Decrement operator; decrements a value by 1 |
! | Logical complement operator; inverts the value of a boolean |
The following program, UnaryDemo , tests the unary operators:
The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version ( ++result ) evaluates to the incremented value, whereas the postfix version ( result++ ) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.
The following program, PrePostDemo , illustrates the prefix/postfix unary increment operator:
Как работает остаток от деления java
Остаток от деления - это целое число, полученное в результате операции деления с остатком. Если остаток от деления равен, то число делится на делитель нацело. В Java остаток от деления одного числа на другое можно получить при помощи оператора %
System.out.println(3 % 2); // => 1 System.out.println(4 % 2); // => 0
Рассмотрим работу оператора на примере. Поделим число 78 на 33. При делении мы получим неполное частное 2 и остаток от деления. Чтобы убедиться в правильности результата, нужно неполное частное умножить на делитель и прибавить остаток от деления: