From 5084eade818d333811c83953c5e495bb5fac98b1 Mon Sep 17 00:00:00 2001 From: Nikolay Gagarinov Date: Thu, 2 Jul 2026 20:22:39 +0500 Subject: [PATCH] =?UTF-8?q?feat(20-arithmetics):=20=D0=BB=D0=BE=D0=BA?= =?UTF-8?q?=D0=B0=D0=BB=D0=B8=20en/es=20=E2=80=94=20=D0=BF=D0=B5=D1=80?= =?UTF-8?q?=D0=B5=D0=B2=D0=BE=D0=B4=20=D0=BF=D0=BE=D0=B4=20=D0=BD=D0=BE?= =?UTF-8?q?=D0=B2=D1=8B=D0=B9=20ru?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - en/: создан для 7 уроков (README, EXERCISE, data.yml) - es/: ресинхрон 6 уроков под ru; 80-linting/es пропущен (в синхроне) - description.en.yml модуля создан - диаграммы (приоритет операций, операнд/оператор, float-погрешность) переведены с сохранением выравнивания Проверки: schema-validate + description-lint — passed (java не менялся). Co-Authored-By: Claude Opus 4.8 (1M context) --- .../20-arithmetics/10-basics/en/EXERCISE.md | 2 + modules/20-arithmetics/10-basics/en/README.md | 117 ++++++++++++++++++ modules/20-arithmetics/10-basics/en/data.yml | 14 +++ modules/20-arithmetics/10-basics/es/README.md | 111 ++++++++++++++--- modules/20-arithmetics/10-basics/es/data.yml | 13 +- .../20-operators/en/EXERCISE.md | 2 + .../20-arithmetics/20-operators/en/README.md | 57 +++++++++ .../20-arithmetics/20-operators/en/data.yml | 21 ++++ .../20-arithmetics/20-operators/es/README.md | 56 ++++++--- .../20-arithmetics/20-operators/es/data.yml | 10 +- .../30-commutative/en/EXERCISE.md | 9 ++ .../30-commutative/en/README.md | 44 +++++++ .../20-arithmetics/30-commutative/en/data.yml | 11 ++ .../30-commutative/es/EXERCISE.md | 4 +- .../30-commutative/es/README.md | 43 +++++-- .../20-arithmetics/30-commutative/es/data.yml | 9 +- .../40-composition/en/EXERCISE.md | 8 ++ .../40-composition/en/README.md | 60 +++++++++ .../20-arithmetics/40-composition/en/data.yml | 5 + .../40-composition/es/EXERCISE.md | 8 +- .../40-composition/es/README.md | 57 +++++++-- .../20-arithmetics/40-composition/es/data.yml | 3 + .../20-arithmetics/50-priority/en/EXERCISE.md | 4 +- .../20-arithmetics/50-priority/en/README.md | 56 +++++++-- .../20-arithmetics/50-priority/en/data.yml | 7 +- .../20-arithmetics/50-priority/es/EXERCISE.md | 2 +- .../20-arithmetics/50-priority/es/README.md | 54 ++++++-- .../20-arithmetics/50-priority/es/data.yml | 5 + .../20-arithmetics/60-float/en/EXERCISE.md | 2 + modules/20-arithmetics/60-float/en/README.md | 59 +++++++++ modules/20-arithmetics/60-float/en/data.yml | 9 ++ .../20-arithmetics/60-float/es/EXERCISE.md | 2 +- modules/20-arithmetics/60-float/es/README.md | 55 +++++--- modules/20-arithmetics/60-float/es/data.yml | 9 +- .../20-arithmetics/80-linting/en/EXERCISE.md | 2 + .../20-arithmetics/80-linting/en/README.md | 37 ++++++ modules/20-arithmetics/80-linting/en/data.yml | 3 + modules/20-arithmetics/description.en.yml | 5 + 38 files changed, 858 insertions(+), 117 deletions(-) create mode 100644 modules/20-arithmetics/10-basics/en/EXERCISE.md create mode 100644 modules/20-arithmetics/10-basics/en/README.md create mode 100644 modules/20-arithmetics/10-basics/en/data.yml create mode 100644 modules/20-arithmetics/20-operators/en/EXERCISE.md create mode 100644 modules/20-arithmetics/20-operators/en/README.md create mode 100644 modules/20-arithmetics/20-operators/en/data.yml create mode 100644 modules/20-arithmetics/30-commutative/en/EXERCISE.md create mode 100644 modules/20-arithmetics/30-commutative/en/README.md create mode 100644 modules/20-arithmetics/30-commutative/en/data.yml create mode 100644 modules/20-arithmetics/40-composition/en/EXERCISE.md create mode 100644 modules/20-arithmetics/40-composition/en/README.md create mode 100644 modules/20-arithmetics/40-composition/en/data.yml create mode 100644 modules/20-arithmetics/60-float/en/EXERCISE.md create mode 100644 modules/20-arithmetics/60-float/en/README.md create mode 100644 modules/20-arithmetics/60-float/en/data.yml create mode 100644 modules/20-arithmetics/80-linting/en/EXERCISE.md create mode 100644 modules/20-arithmetics/80-linting/en/README.md create mode 100644 modules/20-arithmetics/80-linting/en/data.yml create mode 100644 modules/20-arithmetics/description.en.yml diff --git a/modules/20-arithmetics/10-basics/en/EXERCISE.md b/modules/20-arithmetics/10-basics/en/EXERCISE.md new file mode 100644 index 0000000..94aa9b4 --- /dev/null +++ b/modules/20-arithmetics/10-basics/en/EXERCISE.md @@ -0,0 +1,2 @@ + +Print the result of dividing the number *81* by *9*. diff --git a/modules/20-arithmetics/10-basics/en/README.md b/modules/20-arithmetics/10-basics/en/README.md new file mode 100644 index 0000000..0ad7718 --- /dev/null +++ b/modules/20-arithmetics/10-basics/en/README.md @@ -0,0 +1,117 @@ +At the basic level, computers work only with numbers. Even when you write a large application in a modern language, calculations are constantly happening inside. The program adds, subtracts, multiplies, and divides numbers thousands of times per second. + +The total of items in an online store's cart, a character's coordinates in a game, the length of a video in seconds. Behind all of this are ordinary arithmetic operations. + +Fortunately, ordinary school arithmetic is enough to get started. That's where we'll begin. + +## Addition + +In mathematics, a sum is written as 3 + 4. In Java, the expression looks the same. On its own, it doesn't show anything on the screen, so the result needs to be printed. + +To print, we use the familiar command `System.out.println()`. Here is a whole program that adds two numbers and prints the result: + +```java +class App { + public static void main(String[] args) { + System.out.println(3 + 4); + } +} +``` + +First the sum is calculated, then the resulting number is passed into the print command. + +```text +System.out.println(3 + 4); + └─┬─┘ + 7 + +System.out.println(7); → 7 +``` + +After running it, the result appears on the screen: + +```text +7 +``` + +If you put the same expression in quotes, the result changes. In quotes it becomes text, and the string is printed as is: + +```java +System.out.println("3 + 4"); // 3 + 4 +System.out.println(3 + 4); // 7 +``` + +In the first line, Java sees text and prints it literally. In the second, it sees arithmetic and calculates. + +## Other operations + +Besides addition, Java has the whole familiar set of operations: + +| Operation | Symbol | Example | Result | +|----------------|--------|---------|--------| +| Addition | `+` | `2 + 3` | `5` | +| Subtraction | `-` | `7 - 2` | `5` | +| Multiplication | `*` | `4 * 3` | `12` | +| Division | `/` | `8 / 2` | `4` | +| Remainder | `%` | `7 % 3` | `1` | + +Let's print the result of division, and then the result of multiplication: + +```java +System.out.println(8 / 2); // 4 +System.out.println(3 * 3 * 3); // 27 +``` + +Java has no separate operator for exponentiation. When the exponent is small, a number is multiplied by itself the required number of times, as in the example above with `3 * 3 * 3`. + +## Integer division + +There is an important feature related to division in Java. When both numbers are integers, the result is also an integer, and the fractional part is discarded: + +```java +System.out.println(8 / 2); // 4 +System.out.println(7 / 2); // 3 +``` + +In the second example, a calculator would give 3.5. Java divides 7 by 2 as integers and keeps only the integer part, that is 3. The remainder is lost. + +This happens because integers in Java are stored separately from fractional numbers. For working with fractions, Java has a special kind of number. They are called floating-point numbers and are written with a dot, for example `3.5`. For now, integers are enough for us. + +## Remainder + +The `%` operation extracts what remains after integer division. + +```java +System.out.println(7 % 3); // 1 +``` + +Why is it 1? Three fits into seven twice, which gives 6. One is missing to reach seven, and that one is the remainder. + +More examples: + +```java +System.out.println(10 % 4); // 2, four fits into ten twice, 2 left to reach 10 +System.out.println(15 % 5); // 0, five divides 15 evenly +``` + +The remainder helps in many tasks. It's used to check whether a number divides evenly. If the remainder is zero, it divides. This is how even numbers are told apart from odd ones, since the remainder of dividing by 2 is 0 for even numbers and 1 for odd ones. The remainder also helps to count in a circle. The remainder of dividing by 12 works like a clock face, and `13 % 12` gives `1`, because after twelve the count starts over. This operation appears in code all the time. + +## Formatting expressions + +For Java, there's no difference between `3+4` and `3 + 4`. The program understands both variants the same way and adds the numbers in both cases. The difference is only in readability. In programming, it's customary to separate arithmetic operators with spaces, because that makes the expression easier to read: + +```java +3 + 4 +8 / 2 +7 % 3 +``` + +The variant without spaces also works: + +```java +3+4 +8/2 +7%3 +``` + +It looks cramped and is harder on the eyes. Get used to writing with spaces around operators right away. diff --git a/modules/20-arithmetics/10-basics/en/data.yml b/modules/20-arithmetics/10-basics/en/data.yml new file mode 100644 index 0000000..6413ed3 --- /dev/null +++ b/modules/20-arithmetics/10-basics/en/data.yml @@ -0,0 +1,14 @@ +--- +name: Arithmetic operations +tips: + - >- + Separate arithmetic operators from operands with spaces; it's good + programming style. This makes the expression easier to read. + - Division by zero results in an error. + - >- + [Division with remainder](https://en.wikipedia.org/wiki/Euclidean_division) +definitions: + - name: Statement + description: >- + the smallest standalone part of a programming language, a command or a set + of commands. A program is usually a sequence of statements. diff --git a/modules/20-arithmetics/10-basics/es/README.md b/modules/20-arithmetics/10-basics/es/README.md index 4232a59..4993c07 100644 --- a/modules/20-arithmetics/10-basics/es/README.md +++ b/modules/20-arithmetics/10-basics/es/README.md @@ -1,46 +1,117 @@ -A nivel básico, las computadoras operan solo con números. Incluso en aplicaciones de alto nivel, hay muchos números y operaciones dentro de ellas. +A nivel básico, las computadoras trabajan solo con números. Incluso cuando escribes una aplicación grande en un lenguaje moderno, por dentro se realizan cálculos constantemente. El programa suma, resta, multiplica y divide números miles de veces por segundo. -Afortunadamente, para comenzar, es suficiente conocer la aritmética básica, así que empecemos por ahí. +El total de los productos en el carrito de una tienda en línea, las coordenadas de un personaje en un juego, la duración de un vídeo en segundos. Detrás de todo esto están las operaciones aritméticas comunes. -En matemáticas, para sumar dos números, escribimos, por ejemplo, *3 + 4*. En programación, es lo mismo. Aquí hay un programa que suma dos números: +Por suerte, para empezar basta con la aritmética escolar común. Por ahí empezaremos. + +## Suma + +En matemáticas, una suma se escribe como 3 + 4. En Java, la expresión se ve igual. Por sí sola no muestra nada en la pantalla, así que el resultado hay que imprimirlo. + +Para imprimir se usa el conocido comando `System.out.println()`. Aquí tienes un programa completo que suma dos números e imprime el resultado: ```java class App { public static void main(String[] args) { - 3 + 4; + System.out.println(3 + 4); } } ``` -Si ejecutas este programa, se ejecutará en silencio y finalizará. No se mostrará nada en la pantalla. La operación de suma, al igual que las demás operaciones, no hace nada más que sumar. +Primero se calcula la suma, y luego el número obtenido entra dentro del comando de impresión. -Para utilizar el resultado de la suma, debes mostrarlo en la pantalla: - -```java +```text System.out.println(3 + 4); + └─┬─┘ + 7 + +System.out.println(7); → 7 ``` -Después de ejecutarlo, se mostrará el resultado en la pantalla: +Después de ejecutarlo, en la pantalla aparecerá el resultado: ```text 7 ``` -Además de la suma, están disponibles las siguientes operaciones: +Si tomamos la misma expresión entre comillas, el resultado cambia. Entre comillas se obtiene texto, y en la pantalla saldrá la cadena tal cual: + +```java +System.out.println("3 + 4"); // 3 + 4 +System.out.println(3 + 4); // 7 +``` + +En la primera línea, Java ve texto y lo imprime literalmente. En la segunda ve aritmética y calcula. -* `*` — multiplicación -* `/` — división -* `-` — resta -* `%` — [módulo](https://es.wikipedia.org/wiki/Operaci%C3%B3n_m%C3%B3dulo) +## Otras operaciones -Ahora, vamos a mostrar en pantalla el resultado de una división y luego el resultado de elevar un número a una potencia: +Además de la suma, en Java existe todo el conjunto habitual de operaciones: + +| Operación | Símbolo | Ejemplo | Resultado | +|----------------------|---------|---------|-----------| +| Suma | `+` | `2 + 3` | `5` | +| Resta | `-` | `7 - 2` | `5` | +| Multiplicación | `*` | `4 * 3` | `12` | +| División | `/` | `8 / 2` | `4` | +| Resto de la división | `%` | `7 % 3` | `1` | + +Mostremos el resultado de una división y luego el resultado de una multiplicación: ```java -System.out.println(8 / 2); -System.out.println(3 * 3 * 3); +System.out.println(8 / 2); // 4 +System.out.println(3 * 3 * 3); // 27 ``` -```text -4 -27 +En Java no hay un operador aparte para la potenciación. Cuando el exponente es pequeño, se multiplica el número por sí mismo la cantidad de veces necesaria, como en el ejemplo anterior con `3 * 3 * 3`. + +## División de números enteros + +Con la división en Java hay una particularidad importante. Cuando ambos números son enteros, el resultado también es entero, y la parte fraccionaria se descarta: + +```java +System.out.println(8 / 2); // 4 +System.out.println(7 / 2); // 3 ``` + +En el segundo ejemplo, en una calculadora saldría 3.5. Java divide 7 entre 2 de forma entera y deja solo la parte entera, es decir, 3. El resto se pierde. + +Esto ocurre porque en Java los números enteros se almacenan por separado de los fraccionarios. Para trabajar con fracciones, Java tiene un tipo especial de números. Se llaman números de punto flotante y se escriben con un punto, por ejemplo `3.5`. Por ahora nos bastan los enteros. + +## Resto de la división + +La operación `%` extrae lo que queda después de una división entera. + +```java +System.out.println(7 % 3); // 1 +``` + +¿Por qué sale 1? El tres cabe dos veces en el siete, lo que da 6. Falta uno para llegar al siete, y ese uno es el resto. + +Más ejemplos: + +```java +System.out.println(10 % 4); // 2, el cuatro cabe dos veces en el diez, quedan 2 para llegar a 10 +System.out.println(15 % 5); // 0, el cinco divide 15 exactamente +``` + +El resto ayuda en muchas tareas. Con él se comprueba si un número se divide de forma exacta. Si el resto es cero, entonces se divide. Así se distinguen los números pares de los impares, ya que el resto de dividir entre 2 es 0 en los pares y 1 en los impares. Y además el resto ayuda a contar en círculo. El resto de dividir entre 12 funciona como la esfera de un reloj, y `13 % 12` da `1`, porque después del doce la cuenta empieza de nuevo. Esta operación aparece en el código constantemente. + +## Formato de las expresiones + +Para Java no hay diferencia entre `3+4` y `3 + 4`. El programa entiende ambas variantes de la misma manera y en ambos casos suma los números. La diferencia está solo en la legibilidad. En programación se acostumbra a separar los operadores aritméticos con espacios, porque así la expresión se percibe más fácilmente: + +```java +3 + 4 +8 / 2 +7 % 3 +``` + +La variante sin espacios también funciona: + +```java +3+4 +8/2 +7%3 +``` + +Se ve apretada y cuesta más a la vista. Acostúmbrate a escribir desde el principio con espacios alrededor de los operadores. diff --git a/modules/20-arithmetics/10-basics/es/data.yml b/modules/20-arithmetics/10-basics/es/data.yml index af3ad37..841a035 100644 --- a/modules/20-arithmetics/10-basics/es/data.yml +++ b/modules/20-arithmetics/10-basics/es/data.yml @@ -2,5 +2,14 @@ name: Operaciones aritméticas tips: - >- - La división por cero produce un error. Para evitarlo, debes conocer las - estructuras condicionales (las aprenderás en las próximas lecciones). + Separa los operadores aritméticos de los operandos con espacios; es un buen + estilo de programación. Así la expresión se lee con más comodidad. + - La división por cero produce un error. + - >- + [División con resto](https://es.wikipedia.org/wiki/División_euclídea) +definitions: + - name: Instrucción + description: >- + la parte autónoma más pequeña de un lenguaje de programación, un comando o + un conjunto de comandos. Un programa suele ser una secuencia de + instrucciones. diff --git a/modules/20-arithmetics/20-operators/en/EXERCISE.md b/modules/20-arithmetics/20-operators/en/EXERCISE.md new file mode 100644 index 0000000..4218525 --- /dev/null +++ b/modules/20-arithmetics/20-operators/en/EXERCISE.md @@ -0,0 +1,2 @@ + +Write a program that calculates the difference between the numbers `6` and `-81` and prints the answer on the screen. diff --git a/modules/20-arithmetics/20-operators/en/README.md b/modules/20-arithmetics/20-operators/en/README.md new file mode 100644 index 0000000..9c95f95 --- /dev/null +++ b/modules/20-arithmetics/20-operators/en/README.md @@ -0,0 +1,57 @@ +First, let's go over the basic terminology. A sign of an operation like `+` is called an **operator**. An operator specifies an action, for example addition: + +```java +System.out.println(8 + 2); // 10 +``` + +Here `+` works as an operator, and the numbers `8` and `2` are called **operands**. Operands are the values to which the operator applies an action. + +```text +operand operator operand result + 8 + 2 → 10 + 5 - 3 → 2 + 4 * 3 → 12 +``` + +Addition has two operands. One is to the left of the sign, the other to the right. Operations with two operands are called **binary**. If you omit at least one operand, the program won't compile and will produce a syntax error: + +```java +System.out.println(3 + ); // you can't write it like this +``` + +Operations aren't always binary. There are also unary ones, with one operand, and ternary ones, with three. + +## Unary minus + +The same sign sometimes means different operations. Look at the minus: + +```java +System.out.println(-3); // -3 +``` + +Here the minus stands before a single number and works as a unary operator. It takes the number `3` and returns its opposite, that is `-3`. + +When the minus stands between two numbers, it's already subtraction: + +```java +System.out.println(5 - 2); // 3 +System.out.println(10 - 7); // 3 +``` + +The difference is especially noticeable with negative numbers: + +```java +System.out.println(5 - -2); // 7 +``` + +On the left there's subtraction `5 - (...)`, and on the right the unary minus turns `2` into a negative number. This gives `5 - (-2)`, which results in `7`. Minus times minus gives plus, exactly as in school. + +The meaning of the minus depends on its neighbors. Next to two numbers it's subtraction, before a single number it's a sign change. The notation `-3` is both the number itself and an operator with an operand. Many programming languages have the same logic, so it's a familiar thing. + +The plus can also be unary. The notation `+5` only emphasizes that the number is positive and doesn't change its value: + +```java +System.out.println(+5); // 5 +``` + +The other arithmetic operators `*`, `/`, and `%` are always binary; they need two operands. Only plus and minus can work in two roles at once, both as binary and as unary. diff --git a/modules/20-arithmetics/20-operators/en/data.yml b/modules/20-arithmetics/20-operators/en/data.yml new file mode 100644 index 0000000..a535060 --- /dev/null +++ b/modules/20-arithmetics/20-operators/en/data.yml @@ -0,0 +1,21 @@ +--- +name: Operators +tips: + - >- + Separate arithmetic operators from operands with spaces; it's good + programming style. +definitions: + - name: Arithmetic operation + description: addition, subtraction, multiplication, and division. + - name: Operator + description: >- + a special symbol that creates an operation. For example, `+` creates the + addition operation. + - name: Operand + description: 'an object that participates in an operation. `3 * 6`: here 3 and 6 are the operands.' + - name: Unary operation + description: >- + an operation with one operand. For example, `-3` is a unary operation for + getting the number opposite to three. + - name: Binary operation + description: an operation with two operands. For example, `3 + 9`. diff --git a/modules/20-arithmetics/20-operators/es/README.md b/modules/20-arithmetics/20-operators/es/README.md index f6b11fa..9358de0 100644 --- a/modules/20-arithmetics/20-operators/es/README.md +++ b/modules/20-arithmetics/20-operators/es/README.md @@ -1,33 +1,57 @@ -Antes de continuar, vamos a repasar la terminología básica. Un signo de operación, como `+`, se llama operador. Un **operador** es simplemente un símbolo que realiza una operación, como la suma: +Primero repasemos la terminología básica. Un signo de operación como `+` se llama **operador**. Un operador define una acción, por ejemplo la suma: ```java -System.out.println(8 + 2); // => 10 +System.out.println(8 + 2); // 10 ``` -En este ejemplo, `+` es el operador, y los números *8* y *2* son los **operandos**. +Aquí `+` funciona como operador, y los números `8` y `2` se llaman **operandos**. Los operandos son los valores a los que el operador aplica una acción. -En el caso de la suma, tenemos dos operandos: - -* Uno a la izquierda -* Otro a la derecha del signo *+* +```text +operando operador operando resultado + 8 + 2 → 10 + 5 - 3 → 2 + 4 * 3 → 12 +``` -Las operaciones que requieren dos operandos se llaman **binarias**. Si falta al menos un operando, el programa dará un error de sintaxis. Por ejemplo: +La suma tiene dos operandos. Uno está a la izquierda del signo, el otro a la derecha. Las operaciones con dos operandos se llaman **binarias**. Si se omite al menos un operando, el programa no compilará y dará un error de sintaxis: +```java +System.out.println(3 + ); // no se puede escribir así ``` -`3 + ;` + +Las operaciones no siempre son binarias. También existen las unarias, con un operando, y las ternarias, con tres. + +## Menos unario + +El mismo signo a veces significa operaciones diferentes. Fíjate en el menos: + +```java +System.out.println(-3); // -3 ``` -Las operaciones no solo pueden ser binarias. También pueden ser: +Aquí el menos está delante de un solo número y funciona como operador unario. Toma el número `3` y devuelve su opuesto, es decir, `-3`. -* Unarias: con un solo operando -* Ternarias: con tres operandos +Cuando el menos está entre dos números, ya es una resta: -Además, los operadores pueden tener la misma apariencia pero representar operaciones diferentes: +```java +System.out.println(5 - 2); // 3 +System.out.println(10 - 7); // 3 +``` + +La diferencia se nota especialmente con los números negativos: ```java -System.out.println(-3); // => -3 +System.out.println(5 - -2); // 7 ``` -En el ejemplo anterior, se aplica una operación unaria al número *3*. El operador "menos" antes del tres le indica al intérprete que tome el número *3* y encuentre su opuesto, es decir, *-3*. +A la izquierda hay una resta `5 - (...)`, y a la derecha el menos unario convierte `2` en un número negativo. Resulta `5 - (-2)`, y eso da `7`. Menos por menos da más, igual que en la escuela. + +El significado del menos depende de sus vecinos. Junto a dos números es una resta, delante de un solo número es un cambio de signo. La notación `-3` es a la vez el número en sí y un operador con un operando. Muchos lenguajes de programación tienen la misma lógica, así que es algo habitual. + +El más también puede ser unario. La notación `+5` solo resalta que el número es positivo y no cambia su valor: + +```java +System.out.println(+5); // 5 +``` -Esto puede ser un poco confuso, ya que *-3* es tanto un número en sí mismo como un operador con un operando, pero así es la estructura de los lenguajes de programación. +Los demás operadores aritméticos `*`, `/` y `%` son siempre binarios; necesitan dos operandos. Solo el más y el menos pueden funcionar en dos roles a la vez, tanto binarios como unarios. diff --git a/modules/20-arithmetics/20-operators/es/data.yml b/modules/20-arithmetics/20-operators/es/data.yml index 2744434..d40db0b 100644 --- a/modules/20-arithmetics/20-operators/es/data.yml +++ b/modules/20-arithmetics/20-operators/es/data.yml @@ -1,16 +1,18 @@ --- name: Operadores +tips: + - >- + Separa los operadores aritméticos de los operandos con espacios; es un buen + estilo de programación. definitions: - name: Operación aritmética description: suma, resta, multiplicación y división. - name: Operador description: >- - un símbolo especial que crea una operación. Por ejemplo, `+` crea una + un símbolo especial que crea una operación. Por ejemplo, `+` crea la operación de suma. - name: Operando - description: >- - un objeto que participa en una operación. `3 * 6`: aquí, 3 y 6 son - operandos. + description: 'un objeto que participa en una operación. `3 * 6`: aquí 3 y 6 son los operandos.' - name: Operación unaria description: >- una operación con un solo operando. Por ejemplo, `-3` es una operación diff --git a/modules/20-arithmetics/30-commutative/en/EXERCISE.md b/modules/20-arithmetics/30-commutative/en/EXERCISE.md new file mode 100644 index 0000000..499657e --- /dev/null +++ b/modules/20-arithmetics/30-commutative/en/EXERCISE.md @@ -0,0 +1,9 @@ + +This task isn't directly related to the topic of the lesson. But it will be useful to practice arithmetic operations and printing to the screen. + +Write a program that calculates and sequentially prints the values of the following mathematical expressions: "3 multiplied by 5" and "-8 divided by -4". + +```text +15 +2 +``` diff --git a/modules/20-arithmetics/30-commutative/en/README.md b/modules/20-arithmetics/30-commutative/en/README.md new file mode 100644 index 0000000..3c5d934 --- /dev/null +++ b/modules/20-arithmetics/30-commutative/en/README.md @@ -0,0 +1,44 @@ +We all remember the phrase from school "changing the order of the addends doesn't change the sum". This is one of the basic principles of arithmetic, and it's called the **commutative law**. + +## What commutativity is + +An operation is called commutative when the order of the operands doesn't affect the result. Swap the values and you get the same answer. Addition is commutative: + +```java +System.out.println(3 + 2); // 5 +System.out.println(2 + 3); // 5 +``` + +The identical result confirms commutativity. + +```text +2 + 3 = 5 3 + 2 = 5 +└──────────┬─────────┘ + the same result + +2 - 3 = -1 3 - 2 = 1 +└──────────┬─────────┘ + different result +``` + +## Non-commutative operations + +Not all operations work this way. Subtraction changes the result when the operands are swapped: + +```java +System.out.println(2 - 3); // -1 +System.out.println(3 - 2); // 1 +``` + +Division is also non-commutative, and in Java this is especially clear: + +```java +System.out.println(8 / 2); // 4 +System.out.println(2 / 8); // 0 +``` + +In the first case, eight is divided by two and gives `4`. In the second, two is divided by eight. Not a single whole eight fits into two, so integer division gives `0`. + +## In programming it's the same as in arithmetic + +Java follows the same mathematical rules as school arithmetic. And since most operations are non-commutative, the order of operands always matters. Pay attention to it, especially with an unfamiliar operation, and check the order with an example instead of guessing. diff --git a/modules/20-arithmetics/30-commutative/en/data.yml b/modules/20-arithmetics/30-commutative/en/data.yml new file mode 100644 index 0000000..922c427 --- /dev/null +++ b/modules/20-arithmetics/30-commutative/en/data.yml @@ -0,0 +1,11 @@ +--- +name: Commutative operation +tips: + - >- + [More about commutativity](https://en.wikipedia.org/wiki/Commutative_property) +definitions: + - name: Commutativity + description: >- + a property of an operation in which changing the order of the operands + doesn't affect the result. For example, addition is commutative: changing + the order of the addends doesn't change the sum. diff --git a/modules/20-arithmetics/30-commutative/es/EXERCISE.md b/modules/20-arithmetics/30-commutative/es/EXERCISE.md index 4b6e4fe..78330f2 100644 --- a/modules/20-arithmetics/30-commutative/es/EXERCISE.md +++ b/modules/20-arithmetics/30-commutative/es/EXERCISE.md @@ -1,7 +1,7 @@ -Esta tarea no está directamente relacionada con el tema de la lección. Sin embargo, será útil practicar con operaciones aritméticas y mostrar resultados en pantalla. +Esta tarea no está directamente relacionada con el tema de la lección. Pero será útil practicar las operaciones aritméticas y la salida por pantalla. -Escriba un programa que calcule y muestre en pantalla los valores de las siguientes expresiones matemáticas de forma secuencial: "3 multiplicado por 5" y "-8 dividido por -4". +Escribe un programa que calcule y muestre en pantalla, de forma sucesiva, los valores de las siguientes expresiones matemáticas: «3 multiplicado por 5» y «-8 dividido entre -4». ```text 15 diff --git a/modules/20-arithmetics/30-commutative/es/README.md b/modules/20-arithmetics/30-commutative/es/README.md index e278279..8f15775 100644 --- a/modules/20-arithmetics/30-commutative/es/README.md +++ b/modules/20-arithmetics/30-commutative/es/README.md @@ -1,15 +1,44 @@ -Todos recordamos de la escuela: "el resultado no cambia al cambiar el orden de los sumandos". Este es uno de los principios básicos e intuitivos de la aritmética, conocido como la **ley conmutativa**. +Todos recordamos de la escuela la frase "el orden de los sumandos no altera la suma". Este es uno de los principios básicos de la aritmética, y se llama **ley conmutativa**. -Una operación binaria se considera conmutativa si se obtiene el mismo resultado al intercambiar los operandos. Es evidente que la suma es una operación conmutativa: +## Qué es la conmutatividad -```text -3 + 2 = 2 + 3 +Una operación se llama conmutativa cuando el orden de los operandos no afecta al resultado. Intercambias los valores y obtienes la misma respuesta. La suma es conmutativa: + +```java +System.out.println(3 + 2); // 5 +System.out.println(2 + 3); // 5 ``` -Sin embargo, la resta no es una operación conmutativa: +El resultado idéntico confirma la conmutatividad. ```text -2 - 3 ≠ 3 - 2 +2 + 3 = 5 3 + 2 = 5 +└──────────┬─────────┘ + el mismo resultado + +2 - 3 = -1 3 - 2 = 1 +└──────────┬─────────┘ + resultado distinto +``` + +## Operaciones no conmutativas + +No todas las operaciones funcionan así. La resta cambia el resultado cuando se intercambian los operandos: + +```java +System.out.println(2 - 3); // -1 +System.out.println(3 - 2); // 1 +``` + +La división también es no conmutativa, y en Java esto se ve con especial claridad: + +```java +System.out.println(8 / 2); // 4 +System.out.println(2 / 8); // 0 ``` -En programación, esta ley funciona de la misma manera que en aritmética. Además, la mayoría de las operaciones no son conmutativas. Por lo tanto, siempre preste atención al orden con el que trabaja. +En el primer caso, el ocho se divide entre el dos y da `4`. En el segundo, el dos se divide entre el ocho. En el dos no cabe ni un solo ocho entero, por eso al dividir números enteros se obtiene `0`. + +## En programación es igual que en aritmética + +Java sigue las mismas reglas matemáticas que la aritmética escolar. Y como la mayoría de las operaciones no son conmutativas, el orden de los operandos siempre importa. Préstale atención, sobre todo con una operación desconocida, y comprueba el orden con un ejemplo en lugar de adivinar. diff --git a/modules/20-arithmetics/30-commutative/es/data.yml b/modules/20-arithmetics/30-commutative/es/data.yml index 105310d..6ef1151 100644 --- a/modules/20-arithmetics/30-commutative/es/data.yml +++ b/modules/20-arithmetics/30-commutative/es/data.yml @@ -1,8 +1,11 @@ --- name: Operación conmutativa +tips: + - >- + [Más sobre la conmutatividad](https://es.wikipedia.org/wiki/Conmutatividad) definitions: - name: Conmutatividad description: >- - propiedad de una operación en la que el cambio de orden de los operandos - no afecta al resultado. Por ejemplo, la suma es una operación conmutativa: - el resultado no cambia al cambiar el orden de los sumandos. + una propiedad de una operación en la que cambiar el orden de los operandos + no afecta al resultado. Por ejemplo, la suma es conmutativa: el resultado + no cambia al cambiar el orden de los sumandos. diff --git a/modules/20-arithmetics/40-composition/en/EXERCISE.md b/modules/20-arithmetics/40-composition/en/EXERCISE.md new file mode 100644 index 0000000..d1c1360 --- /dev/null +++ b/modules/20-arithmetics/40-composition/en/EXERCISE.md @@ -0,0 +1,8 @@ + +Implement a program that calculates the value of the expression `8 / 2 + 5 - -3 / 2` and prints the result on the screen. Don't calculate anything yourself; your program must perform all the calculations on its own. +```text +10 +``` +Note that the interpreter performs arithmetic calculations in the correct order: first division and multiplication, then addition and subtraction. Sometimes this order needs to be changed — that's what the next lesson is about. + +Also note that Java uses integer division by default, `3 / 2` will be `1`. diff --git a/modules/20-arithmetics/40-composition/en/README.md b/modules/20-arithmetics/40-composition/en/README.md new file mode 100644 index 0000000..261dcd2 --- /dev/null +++ b/modules/20-arithmetics/40-composition/en/README.md @@ -0,0 +1,60 @@ +What to do when you need several operations at once in a single line? They are written one after another, and Java processes the expression step by step according to strict rules. + +Let's take an example with only multiplications: + +```java +System.out.println(2 * 4 * 5 * 10); // 400 +``` + +To understand how Java calculates, let's break the expression down step by step: + +- first `2 * 4` is calculated, leaving `8 * 5 * 10` +- then `8 * 5`, leaving `40 * 10` +- the last multiplication gives `400` + +This is how operations combine with each other, and increasingly complex expressions are built from simple actions. + +## What if the operations are different + +As long as the operators are the same, everything goes left to right. But what happens if you mix multiplication and addition? + +```java +System.out.println(2 + 3 * 4); +``` + +Will it be `20` or `14`? The answer is `14`. + +```text +2 + 3 * 4 + └─┬─┘ +2 + 12 +└──┬───┘ + 14 +``` + +Operations have priority, just like in math. Multiplication is performed before addition. So first `3 * 4` is calculated, and only then the two is added. The order can be changed with parentheses. In the expression `(2 + 3) * 4`, first `2 + 3` is added, and then the result `5` is multiplied by `4`, giving `20`. + +The same rule works with subtraction: + +```java +System.out.println(10 - 2 * 3); // 4 +``` + +First the multiplication `2 * 3`, then `10 - 6`, resulting in `4`. + +## Negative numbers inside an expression + +When there's a unary minus in an expression, it's applied to its number before the other operations: + +```java +System.out.println(4 + -2); // 2 +System.out.println(6 - -2); // 8 +``` + +Let's break down the second example. First the unary minus turns `2` into `-2`, then the operation reads as `6 - (-2)`, which gives `8`. It's the same as `6 + 2`. + +## What to remember + +- an expression can consist of several operations +- Java evaluates them step by step, from left to right and taking priority into account +- parentheses let you explicitly set the order of evaluation diff --git a/modules/20-arithmetics/40-composition/en/data.yml b/modules/20-arithmetics/40-composition/en/data.yml new file mode 100644 index 0000000..ff3b286 --- /dev/null +++ b/modules/20-arithmetics/40-composition/en/data.yml @@ -0,0 +1,5 @@ +--- +name: Composition of operations +definitions: + - name: Composition + description: a method of combining several simple operations into one complex operation. diff --git a/modules/20-arithmetics/40-composition/es/EXERCISE.md b/modules/20-arithmetics/40-composition/es/EXERCISE.md index e68af3b..af5e84b 100644 --- a/modules/20-arithmetics/40-composition/es/EXERCISE.md +++ b/modules/20-arithmetics/40-composition/es/EXERCISE.md @@ -1,8 +1,8 @@ -Implementa un programa que calcule el valor de la expresión `8 / 2 + 5 - -3 / 2` y muestre el resultado en pantalla. No calcules nada por tu cuenta, tu programa debe realizar todos los cálculos por sí mismo. +Implementa un programa que calcule el valor de la expresión `8 / 2 + 5 - -3 / 2` y muestre el resultado en pantalla. No calcules nada por tu cuenta; tu programa debe realizar todos los cálculos por sí mismo. ```text 10 -```text -Observa que el intérprete realiza las operaciones aritméticas en el orden correcto: primero la división y la multiplicación, luego la suma y la resta. A veces es necesario cambiar este orden, lo veremos en la siguiente lección. +``` +Ten en cuenta que el intérprete realiza los cálculos aritméticos en el orden correcto: primero la división y la multiplicación, luego la suma y la resta. A veces este orden hay que cambiarlo, y de eso trata la próxima lección. -También ten en cuenta que en Java, la división entera es la que se utiliza por defecto, `3 / 2` será `1`. +También ten en cuenta que en Java se usa por defecto la división entera, `3 / 2` será `1`. diff --git a/modules/20-arithmetics/40-composition/es/README.md b/modules/20-arithmetics/40-composition/es/README.md index aae17ba..d06b066 100644 --- a/modules/20-arithmetics/40-composition/es/README.md +++ b/modules/20-arithmetics/40-composition/es/README.md @@ -1,25 +1,60 @@ -¿Qué pasa si necesitamos calcular una expresión como *3 + 5 - 2*? Así es como lo escribiríamos: +¿Qué hacer cuando en una misma línea se necesitan varias operaciones a la vez? Se escriben una tras otra, y Java procesa la expresión paso a paso siguiendo reglas estrictas. + +Tomemos un ejemplo solo con multiplicaciones: ```java -System.out.println(3 + 5 - 2); // 3 + 5 - 2 => 8 - 2 => 6 +System.out.println(2 * 4 * 5 * 10); // 400 ``` -Observa que la computadora realiza las operaciones aritméticas en el orden correcto: primero la división y la multiplicación, luego la suma y la resta. A veces es necesario cambiar este orden, lo veremos más adelante. +Para entender cómo calcula Java, analicemos la expresión paso a paso: + +- primero se calcula `2 * 4`, y queda `8 * 5 * 10` +- luego `8 * 5`, y queda `40 * 10` +- la última multiplicación da `400` + +Así las operaciones se conectan entre sí, y a partir de acciones simples se construyen expresiones cada vez más complejas. + +## ¿Y si las operaciones son diferentes? -Otro ejemplo: +Mientras los operadores son iguales, todo va de izquierda a derecha. ¿Y qué pasa si mezclamos multiplicación y suma? ```java -System.out.println(2 * 4 * 5 * 10); // 2 * 4 * 5 * 10 => 8 * 5 * 10 => 40 * 10 => 400 +System.out.println(2 + 3 * 4); ``` -Como puedes ver, las operaciones se pueden combinar entre sí y así calcular expresiones compuestas más complejas. Para entender cómo se realizan los cálculos dentro del intérprete, analicemos un ejemplo: +¿Saldrá `20` o `14`? La respuesta es `14`. ```text -2 * 4 * 5 * 10 +2 + 3 * 4 + └─┬─┘ +2 + 12 +└──┬───┘ + 14 +``` + +Las operaciones tienen una prioridad, igual que en matemáticas. La multiplicación se realiza antes que la suma. Por eso primero se calcula `3 * 4`, y solo después se suma el dos. El orden se puede cambiar con paréntesis. En la expresión `(2 + 3) * 4` primero se suma `2 + 3`, y el resultado `5` se multiplica por `4`, y sale `20`. + +La misma regla funciona con la resta: + +```java +System.out.println(10 - 2 * 3); // 4 +``` + +Primero la multiplicación `2 * 3`, luego `10 - 6`, resultado `4`. + +## Números negativos dentro de una expresión + +Cuando en una expresión hay un menos unario, se aplica a su número antes que las demás operaciones: + +```java +System.out.println(4 + -2); // 2 +System.out.println(6 - -2); // 8 ``` -En este ejemplo: +Analicemos el segundo ejemplo. Primero el menos unario convierte `2` en `-2`, luego la operación se lee como `6 - (-2)`, y eso da `8`. Es lo mismo que `6 + 2`. + +## Qué hay que recordar -1. Primero calculamos *2 * 4* y obtenemos la expresión *8 * 5 * 10* -2. Luego multiplicamos *8 * 5*. Al final tenemos *40 * 10* -3. Finalmente, se realiza la última multiplicación y se obtiene el resultado *400* +- una expresión puede constar de varias operaciones +- Java las evalúa paso a paso, de izquierda a derecha y teniendo en cuenta la prioridad +- los paréntesis permiten fijar explícitamente el orden de los cálculos diff --git a/modules/20-arithmetics/40-composition/es/data.yml b/modules/20-arithmetics/40-composition/es/data.yml index 6a5ec94..7f37f42 100644 --- a/modules/20-arithmetics/40-composition/es/data.yml +++ b/modules/20-arithmetics/40-composition/es/data.yml @@ -1,2 +1,5 @@ --- name: Composición de operaciones +definitions: + - name: Composición + description: un método para combinar varias operaciones simples en una operación compleja. diff --git a/modules/20-arithmetics/50-priority/en/EXERCISE.md b/modules/20-arithmetics/50-priority/en/EXERCISE.md index 6cd0475..8f1f11e 100644 --- a/modules/20-arithmetics/50-priority/en/EXERCISE.md +++ b/modules/20-arithmetics/50-priority/en/EXERCISE.md @@ -1,4 +1,4 @@ -Consider an expression: `70 * 3 + 4 / 8 + 2`. +You are given the expression `70 * 3 + 4 / 8 + 2`. -Place the brackets correctly, so that both additions (`3 + 4` и `8 + 2`) are calculated first. Print the result onto the screen. +Place the parentheses so that both additions (`3 + 4` and `8 + 2`) are calculated first. Print the result on the screen. diff --git a/modules/20-arithmetics/50-priority/en/README.md b/modules/20-arithmetics/50-priority/en/README.md index 84744c9..8803089 100644 --- a/modules/20-arithmetics/50-priority/en/README.md +++ b/modules/20-arithmetics/50-priority/en/README.md @@ -1,32 +1,64 @@ -What is the result of `2 + 2 * 2`? +Look at the expression `2 + 2 * 2` and calculate the answer in your head. The correct answer is `6`. If you got `8`, this lesson is for you. -It's `6`. +```java +System.out.println(2 + 2 * 2); // 6 +``` + +The result is `6`, not `8` at all, because of operator priority. Priority determines the order in which operations are performed. Multiplication and division come before addition and subtraction: + +```text +Operator priority (from highest to lowest): + + * / % multiplication, division, remainder + ↓ + + - addition, subtraction +``` + +That's why in the example above, `2 * 2` is calculated first, and only then the two is added to the result. + +When operations of the same priority are next to each other, they are performed from left to right: + +```java +System.out.println(8 / 2 * 3); // 12, first 8 / 2 = 4, then 4 * 3 = 12 +``` + +## Controlling the order of operations -If you thought it's `8`, then this lesson is for you ;-) In primary school you've learned about operation priority. Priority defines the order of operations in complex expressions. For example, multiplication and division have higher priority than addition or division. So, 2 + 3 * 2 is `8`. +Sometimes calculations need to go differently from what priority dictates. Then the order is set with parentheses, exactly as in school: -But sometimes we want different, non-standard order. Just like in math, we can use brackets to change the order, like so: `(2 + 2) * 2`. +```java +System.out.println((2 + 2) * 2); // 8 +``` -Here are few more examples: +Here the parentheses force `2 + 2` to be added first, and only then multiplied by two. + +Parentheses can be placed around any part of an expression and nested inside one another any number of times: ```java -System.out.println(3 * (4 - 2)); // => 6 -System.out.println(7 * 3 + (4 / 2) - (8 + (2 - 1))); // => 14 +System.out.println(3 * (4 - 2)); // 6 +System.out.println(7 * 3 + (4 / 2) - (8 + (2 - 1))); // 14 ``` -Be sure to pair all the brackets in correct order. This is often the problem for both beginners and experienced programmers alike. To make things easier, put both opening and closing brackets, and then type the stuff inside. The editor on our website (and most code editors) do that by default automatically: you type `(`, and the editor adds `)`. This works for some other symbols, like quotation marks, for example. We'll talk about them later. +In the second example, the parentheses are calculated first. `4 / 2` gives `2`, and `8 + (2 - 1)` gives `9`. That leaves `21 + 2 - 9`, resulting in `14`. + +Remember one rule. Always close your parentheses. An unclosed parenthesis leads to an error, and even experienced programmers forget the closing one. + +> Write parentheses as a pair right away. For example, type `()`, and then fill in the inside. Most code editors (including ours) add the closing parenthesis themselves as soon as you type the opening one. + +## Parentheses for readability -Sometimes an expression is too complication to understand visually. Feel free to put brackets even if then won't change the priority, but will make things clearer: +Sometimes an expression works correctly but looks confusing. In such cases, parentheses are added for clarity. They don't affect the result, but they make it easier to read. Before: ```java -System.out.println(8 / 2 + 5 - -3 / 2); // => 11 +System.out.println(8 / 2 + 5 - -4 / 2); // 11 ``` After: ```java -System.out.println(((8 / 2) + 5) - (-3 / 2)); // => 11 +System.out.println(((8 / 2) + 5) - (-4 / 2)); // 11 ``` -Remember: code is for people, because it'll be read by people, and machines will only execute it. The only thing that matters for the machines is the correctness of code. They don't distinguish between "clear" or "confusing". +Code is written and read by people, while the machine only executes it. For the machine there's no more or less understandable code; it's enough for the code to be syntactically correct. A tidy expression with parentheses helps the person, especially when working in a team and when analyzing errors. diff --git a/modules/20-arithmetics/50-priority/en/data.yml b/modules/20-arithmetics/50-priority/en/data.yml index 0ee5d79..cd2079d 100644 --- a/modules/20-arithmetics/50-priority/en/data.yml +++ b/modules/20-arithmetics/50-priority/en/data.yml @@ -1,2 +1,7 @@ --- -name: Priority +name: Operator priority +definitions: + - name: Expression + description: >- + a sequence of actions on data that produces a result suitable for further + use. diff --git a/modules/20-arithmetics/50-priority/es/EXERCISE.md b/modules/20-arithmetics/50-priority/es/EXERCISE.md index 333a0f2..79a0a6d 100644 --- a/modules/20-arithmetics/50-priority/es/EXERCISE.md +++ b/modules/20-arithmetics/50-priority/es/EXERCISE.md @@ -1,4 +1,4 @@ Dada la expresión `70 * 3 + 4 / 8 + 2`. -Coloca paréntesis de manera que ambas sumas (`3 + 4` y `8 + 2`) se calculen primero. Muestra el resultado en pantalla. +Coloca los paréntesis de modo que ambas sumas (`3 + 4` y `8 + 2`) se calculen en primer lugar. Muestra el resultado en pantalla. diff --git a/modules/20-arithmetics/50-priority/es/README.md b/modules/20-arithmetics/50-priority/es/README.md index 8a122ff..2afdc9c 100644 --- a/modules/20-arithmetics/50-priority/es/README.md +++ b/modules/20-arithmetics/50-priority/es/README.md @@ -1,36 +1,64 @@ -Observa detenidamente la expresión *2 + 2 * 2* y calcula mentalmente el resultado. La respuesta correcta es *6*. Si obtuviste *8*, entonces esta lección es para ti. +Mira la expresión `2 + 2 * 2` y calcula la respuesta mentalmente. La respuesta correcta es `6`. Si te salió `8`, esta lección es para ti. -En matemáticas escolares, estudiamos el concepto de "prioridad de la operación". La prioridad determina en qué secuencia deben realizarse las operaciones. +```java +System.out.println(2 + 2 * 2); // 6 +``` -Por ejemplo, la multiplicación y la división tienen mayor prioridad que la suma y la resta: +El resultado es `6`, y no `8`, debido a la prioridad de las operaciones. La prioridad determina en qué orden se realizan las acciones. La multiplicación y la división van antes que la suma y la resta: ```text -2 + 3 * 2 = 8 +Prioridad de las operaciones (de mayor a menor): + + * / % multiplicación, división, resto + ↓ + + - suma, resta ``` -Sin embargo, a menudo los cálculos deben realizarse en un orden diferente al de la prioridad estándar. En situaciones complicadas, se puede especificar la prioridad utilizando paréntesis, al igual que en la escuela, por ejemplo: +Por eso, en el ejemplo anterior primero se calcula `2 * 2`, y solo después se suma el dos al resultado. + +Cuando hay operaciones de la misma prioridad juntas, se realizan de izquierda a derecha: +```java +System.out.println(8 / 2 * 3); // 12, primero 8 / 2 = 4, luego 4 * 3 = 12 ``` -(2 + 2) * 2 + +## Control del orden de las operaciones + +A veces los cálculos deben ir de una forma distinta a la que dicta la prioridad. Entonces el orden se define con paréntesis, igual que en la escuela: + +```java +System.out.println((2 + 2) * 2); // 8 ``` -Los paréntesis se pueden colocar alrededor de cualquier operación. Pueden anidarse tantas veces como sea necesario. Aquí tienes un par de ejemplos: +Aquí los paréntesis obligan a sumar primero `2 + 2`, y solo después a multiplicar por dos. + +Los paréntesis se pueden poner alrededor de cualquier parte de una expresión y anidar unos dentro de otros tantas veces como se quiera: ```java -System.out.println(3 * (4 - 2)); // => 6 -System.out.println(7 * 3 + (4 / 2) - (8 + (2 - 1))); // => 14 +System.out.println(3 * (4 - 2)); // 6 +System.out.println(7 * 3 + (4 / 2) - (8 + (2 - 1))); // 14 ``` -A veces, una expresión puede ser difícil de comprender visualmente. En ese caso, se pueden agregar paréntesis para hacerla más clara, aunque no afectarán la prioridad: +En el segundo ejemplo primero se calculan los paréntesis. `4 / 2` da `2`, y `8 + (2 - 1)` da `9`. Queda `21 + 2 - 9`, y al final `14`. + +Recuerda una regla. Cierra siempre los paréntesis. Un paréntesis sin cerrar provoca un error, y hasta los programadores experimentados se olvidan del de cierre. + +> Escribe los paréntesis en pareja de inmediato. Por ejemplo, escribe `()` y luego rellena la parte interior. La mayoría de los editores de código (incluido el nuestro) añaden ellos mismos el paréntesis de cierre en cuanto escribes el de apertura. + +## Paréntesis para la legibilidad + +A veces una expresión funciona correctamente, pero se ve enredada. En esos casos se añaden paréntesis para mayor claridad. No afectan al resultado, pero se vuelve más cómodo de leer. Antes: + ```java -System.out.println(8 / 2 + 5 - -4 / 2); // => 11 +System.out.println(8 / 2 + 5 - -4 / 2); // 11 ``` Después: + ```java -System.out.println(((8 / 2) + 5) - (-4 / 2)); // => 11 +System.out.println(((8 / 2) + 5) - (-4 / 2)); // 11 ``` -Recuerda: el código se escribe para las personas, porque las personas lo leerán, y las máquinas solo lo ejecutarán. Para las máquinas, no hay código "más" o "menos" comprensible, independientemente de si el código es correcto o no. +El código lo escriben y lo leen personas, mientras que la máquina solo lo ejecuta. Para la máquina no hay código más o menos comprensible; le basta con que el código sea sintácticamente correcto. Una expresión ordenada con paréntesis ayuda a la persona, sobre todo al trabajar en equipo y al analizar errores. diff --git a/modules/20-arithmetics/50-priority/es/data.yml b/modules/20-arithmetics/50-priority/es/data.yml index 3f1d370..8cf3a9b 100644 --- a/modules/20-arithmetics/50-priority/es/data.yml +++ b/modules/20-arithmetics/50-priority/es/data.yml @@ -1,2 +1,7 @@ --- name: Prioridad de las operaciones +definitions: + - name: Expresión + description: >- + una secuencia de acciones sobre los datos que produce un resultado apto + para su uso posterior. diff --git a/modules/20-arithmetics/60-float/en/EXERCISE.md b/modules/20-arithmetics/60-float/en/EXERCISE.md new file mode 100644 index 0000000..fa9774b --- /dev/null +++ b/modules/20-arithmetics/60-float/en/EXERCISE.md @@ -0,0 +1,2 @@ + +Calculate and print on the screen the product of two numbers: *0.39* and *0.22* diff --git a/modules/20-arithmetics/60-float/en/README.md b/modules/20-arithmetics/60-float/en/README.md new file mode 100644 index 0000000..c9e31f8 --- /dev/null +++ b/modules/20-arithmetics/60-float/en/README.md @@ -0,0 +1,59 @@ +In mathematics, there are different kinds of numbers. For example: + +- natural numbers, these are integers from 1 and up +- rational numbers, these are numbers with a dot, for example 0.5, 1.75, 2.25 + +From the standpoint of mathematics, everything here is clear. But from the standpoint of a computer, there's a gulf between these kinds of numbers. Try adding `0.2` and `0.1` in your head. It seems the result will be `0.3`. Here's what Java has to say about it: + +```java +System.out.println(0.2 + 0.1); // 0.30000000000000004 +``` + +Instead of the usual `0.3`, you get `0.30000000000000004`. + +```text +Expectation: 0.1 + 0.2 → 0.3 +Reality: 0.1 + 0.2 → 0.30000000000000004 + └── storage error +``` + +JavaScript, C++, and almost all other languages will produce the same result. + +## Why this happens + +The reason lies in how the computer is built. Memory is finite, while there are infinitely many rational numbers. Between `0.1` and `0.2` there are infinitely many other numbers, and the computer can't store them all. So it approximates the number, trying to fit it into the available bits. + +Integers don't have this trouble; they are bounded from above. The largest integer in Java even has a name: + +```java +System.out.println(Integer.MAX_VALUE); // 2147483647 +``` + +Behind the notation `Integer.MAX_VALUE` hides the extreme value beyond which an ordinary integer in Java does not go. + +This trick doesn't work with rational numbers, since they aren't lined up in a neat chain. Approximate values are called floating point numbers. Their storage and calculations follow the strict IEEE 754 standard, which most languages rely on. + +## When such numbers appear + +Floating point numbers appear more often than you'd think. Here are the two main cases. + +In the first case, you write a number with a dot yourself, for example `0.1`, `2.5`, or `3.14`. + +In the second case, a fractional number is involved in a division: + +```java +System.out.println(1.0 / 2); // 0.5 +System.out.println(2.0 / 3); // 0.6666666666666666 +``` + +Here it's worth recalling integer division. When both operands are integers, Java divides as integers, and `1 / 2` gives `0`. It's enough to make at least one operand fractional, and the result becomes a floating point number. Even when the result looks nice, internally it's still stored approximately. Some fractions, for example `1.0 / 3`, can't be written exactly in the binary system at all. + +## Where this is critical + +Usually a small error doesn't get in the way. But in financial calculations, engineering tasks, and precise comparison of numbers it turns into a problem. An error of a fraction of a cent ruins the final amount, and a long chain of calculations gradually accumulates inaccuracy. + +In real programs, this is dealt with in different ways. Money is often stored in the smallest units, for example in cents, that is, in integers. The result is rounded to the required number of digits. Numbers are compared with a small tolerance. For precise calculations, special data types are used. + +## What to remember + +Operations with floating point numbers aren't always exact, and that's normal. Most programming languages behave this way, and the reason lies in how memory is built. Precision can be controlled by rounding or by comparison with a tolerance. And for money and scientific calculations, it's better to use special data types right away. diff --git a/modules/20-arithmetics/60-float/en/data.yml b/modules/20-arithmetics/60-float/en/data.yml new file mode 100644 index 0000000..a1e4679 --- /dev/null +++ b/modules/20-arithmetics/60-float/en/data.yml @@ -0,0 +1,9 @@ +--- +name: Floating point numbers +tips: + - >- + [What you need to know about floating-point + arithmetic](https://habr.com/ru/articles/112953/) +definitions: + - name: Rational number + description: a number that can be represented as a common fraction. diff --git a/modules/20-arithmetics/60-float/es/EXERCISE.md b/modules/20-arithmetics/60-float/es/EXERCISE.md index 31bfd25..19d3608 100644 --- a/modules/20-arithmetics/60-float/es/EXERCISE.md +++ b/modules/20-arithmetics/60-float/es/EXERCISE.md @@ -1,2 +1,2 @@ -Calcule y muestre en pantalla el producto de dos números: *0.39* y *0.22* +Calcula y muestra en pantalla el producto de dos números: *0.39* y *0.22* diff --git a/modules/20-arithmetics/60-float/es/README.md b/modules/20-arithmetics/60-float/es/README.md index fcc021b..412072f 100644 --- a/modules/20-arithmetics/60-float/es/README.md +++ b/modules/20-arithmetics/60-float/es/README.md @@ -1,34 +1,59 @@ +En matemáticas hay distintos tipos de números. Por ejemplo: -En matemáticas, existen diferentes tipos de números, por ejemplo: +- naturales, que son los números enteros desde 1 en adelante +- racionales, que son los números con punto, por ejemplo 0.5, 1.75, 2.25 -* **Naturales** - son números enteros mayores o iguales a 1 -* **Racionales** - son números con decimales, por ejemplo, 0.5 +Desde el punto de vista de las matemáticas, aquí todo está claro. Pero desde el punto de vista de la computadora, entre estos tipos de números hay un abismo. Intenta sumar mentalmente `0.2` y `0.1`. Parece que saldrá `0.3`. Esto es lo que dice Java al respecto: -Desde la perspectiva de los dispositivos informáticos, hay una brecha entre estos tipos de números. Intentemos sumar dos números racionales: +```java +System.out.println(0.2 + 0.1); // 0.30000000000000004 +``` + +En lugar del habitual `0.3`, se obtiene `0.30000000000000004`. ```text -0.2 + 0.1 = 0.3 +Expectativa: 0.1 + 0.2 → 0.3 +Realidad: 0.1 + 0.2 → 0.30000000000000004 + └── error de almacenamiento ``` -Y ahora veamos qué dice Java al respecto: +El mismo resultado darán JavaScript, C++ y casi todos los demás lenguajes. + +## Por qué ocurre esto + +La causa está en el diseño de la computadora. La memoria es finita, mientras que los números racionales son infinitos. Entre `0.1` y `0.2` caben infinitos números más, y la computadora no puede guardarlos todos. Por eso aproxima el número, tratando de encajarlo en los bits disponibles. + +Con los números enteros no existe este problema; están acotados por arriba. El número entero más grande en Java hasta tiene un nombre: ```java -0.2 + 0.1; // 0.30000000000000004 +System.out.println(Integer.MAX_VALUE); // 2147483647 ``` -La operación de suma de dos números racionales resultó en un cálculo inexacto del resultado. Otros lenguajes de programación también darán el mismo resultado. +Tras la notación `Integer.MAX_VALUE` se esconde el valor límite, más allá del cual un número entero normal en Java no llega. -Este comportamiento se debe a las limitaciones de la capacidad de cálculo. A diferencia de los números, la memoria tiene un límite finito, y un número infinito requeriría una cantidad infinita de memoria para almacenarlo. +Con los números racionales este truco no funciona, ya que no están alineados en una cadena uniforme. Los valores aproximados se llaman números de punto flotante (floating point numbers). Su almacenamiento y los cálculos con ellos se rigen por el estricto estándar IEEE 754, en el que se apoyan la mayoría de los lenguajes. -Con los números naturales, este problema se resuelve estableciendo un límite superior. Hay un número máximo que se puede ingresar: +## Cuándo aparecen estos números + +Los números de punto flotante aparecen más a menudo de lo que parece. Aquí están los dos casos principales. + +En el primer caso, tú mismo escribes un número con punto, por ejemplo `0.1`, `2.5` o `3.14`. + +En el segundo caso, en la división participa un número fraccionario: ```java -System.out.println(Integer.MAX_VALUE); -// => 2147483647 +System.out.println(1.0 / 2); // 0.5 +System.out.println(2.0 / 3); // 0.6666666666666666 ``` -Sin embargo, esto no funciona con los números racionales. La razón es que no están dispuestos en una cadena continua, hay un conjunto infinito de números entre *0.1* y *0.2*. +Aquí conviene recordar la división entera. Cuando ambos operandos son enteros, Java divide de forma entera, y `1 / 2` dará `0`. Basta con hacer que al menos un operando sea fraccionario, y el resultado se convierte en un número de punto flotante. Incluso cuando el resultado se ve bonito, por dentro se almacena de forma aproximada. Algunas fracciones, por ejemplo `1.0 / 3`, no se pueden escribir con exactitud en el sistema binario. + +## Dónde es crítico + +Normalmente un pequeño error no molesta. Pero en los cálculos financieros, las tareas de ingeniería y en la comparación exacta de números se convierte en un problema. Un error de una fracción de céntimo estropea la suma final, y una larga cadena de cálculos va acumulando la imprecisión poco a poco. + +En los programas reales esto se combate de distintas maneras. El dinero se suele guardar en las unidades mínimas, por ejemplo en céntimos, es decir, en números enteros. El resultado se redondea a la cantidad de cifras necesaria. Los números se comparan con una pequeña tolerancia. Para los cálculos exactos se usan tipos de datos especiales. -¿Entonces, cómo se almacenan los números racionales? La mayoría de los lenguajes de programación se basan en un estándar común que describe cómo organizar la memoria en estos casos. +## Qué hay que recordar -Es importante que los desarrolladores comprendan que las operaciones con números de punto flotante no son precisas, pero esta precisión se puede ajustar. Esto significa que al resolver problemas con este tipo de números, es necesario recurrir a trucos especiales que permitan lograr la precisión deseada. +Las operaciones con números de punto flotante no siempre son exactas, y eso es normal. Así se comporta la mayoría de los lenguajes de programación, y la causa está en el diseño de la memoria. La precisión se puede controlar redondeando o comparando con una tolerancia. Y para el dinero y los cálculos científicos es mejor usar directamente tipos de datos especiales. diff --git a/modules/20-arithmetics/60-float/es/data.yml b/modules/20-arithmetics/60-float/es/data.yml index 00b07b2..4ad2ad2 100644 --- a/modules/20-arithmetics/60-float/es/data.yml +++ b/modules/20-arithmetics/60-float/es/data.yml @@ -1,6 +1,9 @@ --- name: Números de punto flotante tips: - - > - [Qué necesitas saber sobre aritmética de punto - flotante](https://habr.com/post/112953/) + - >- + [Qué hay que saber sobre la aritmética de punto + flotante](https://habr.com/ru/articles/112953/) +definitions: + - name: Número racional + description: un número que se puede representar como una fracción común. diff --git a/modules/20-arithmetics/80-linting/en/EXERCISE.md b/modules/20-arithmetics/80-linting/en/EXERCISE.md new file mode 100644 index 0000000..e55c8b3 --- /dev/null +++ b/modules/20-arithmetics/80-linting/en/EXERCISE.md @@ -0,0 +1,2 @@ + +Print on the screen the result of the following calculation: "the difference between the sum of five and two and the product of three and seven". Compare the resulting solution with the teacher's solution in terms of code formatting. diff --git a/modules/20-arithmetics/80-linting/en/README.md b/modules/20-arithmetics/80-linting/en/README.md new file mode 100644 index 0000000..3c14f2d --- /dev/null +++ b/modules/20-arithmetics/80-linting/en/README.md @@ -0,0 +1,37 @@ +Now that we've learned to write simple programs, we can talk a little about how to write them. + +Program code should be formatted in a certain way so that it's clear enough and easy to maintain. + +Special sets of rules — **standards** — describe various aspects of writing code. Specifically in Java, the most widespread standard is the one from [Sun](https://checkstyle.sourceforge.io/checks.html). + +In any programming language there are utilities — the so-called **linters**. They check code for compliance with standards. In Java this is [checkstyle](https://github.com/checkstyle/checkstyle). Take a look at the example: + +```java +System.out.println( "Hello, World!" ); System.out.println("I'm a developer!") ; +``` + +The linter will complain about violations in several places at once: + +* '(' is followed by whitespace. [ParenPad] +* ')' is preceded with whitespace. [ParenPad] +* ';' is preceded with whitespace. [NoWhitespaceBefore] +* Only one statement per line allowed. [OneStatementPerLine] + +Let's analyze these errors: + +* The **ParenPad** rule, shown in square brackets, requires no spaces after the opening parenthesis and before the closing one +* The **NoWhitespaceBefore** rule indicates that you shouldn't put an extra space before the semicolon +* Each new statement should be written on a new line. This is indicated by the *OneStatementPerLine* rule + +Following these rules doesn't affect the result, but it helps to write code that's clearer and easier to grasp. + +Code that follows these rules looks like this: + +```java +System.out.println("Hello, World!"); +System.out.println("I'm a developer!"); +``` + +Now the linter won't complain. What conclusion do we draw? The linter helps write code that will be easier to read and analyze. + +Remember that having a linter doesn't replace analyzing and simplifying code readability yourself. In your future practice on [Hexlet](https://ru.hexlet.io/?utm_source=code-basics&utm_medium=referral&utm_campaign=programs&utm_content=lesson) and in real development, the linter will work and report violations to you. diff --git a/modules/20-arithmetics/80-linting/en/data.yml b/modules/20-arithmetics/80-linting/en/data.yml new file mode 100644 index 0000000..aabf032 --- /dev/null +++ b/modules/20-arithmetics/80-linting/en/data.yml @@ -0,0 +1,3 @@ +--- +name: Linter +tips: [] diff --git a/modules/20-arithmetics/description.en.yml b/modules/20-arithmetics/description.en.yml new file mode 100644 index 0000000..2862b3f --- /dev/null +++ b/modules/20-arithmetics/description.en.yml @@ -0,0 +1,5 @@ +--- + +name: Arithmetic +description: | + Modern programs are created to serve businesses, help in everyday life, and provide entertainment. But at the core of how they work, there are still calculations. The simplest and most basic topic in programming is arithmetic. In this module, we'll translate arithmetic operations into a programming language. We'll recall the school rules from math lessons and talk about operator priority.