-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #11 from k0damaDEV/main
new lessons added
- Loading branch information
Showing
12 changed files
with
182 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
fun main() { | ||
// BEGIN | ||
println(3 * 5) | ||
println(-8 / -4) | ||
// END | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
test: | ||
@ test.sh |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import java.io.ByteArrayOutputStream; | ||
import java.io.PrintStream; | ||
import org.assertj.core.api.Assertions; | ||
|
||
class Test { | ||
public static void main(final String[] args) { | ||
final var expected = "15\n2"; | ||
|
||
MainKt.main(); | ||
|
||
ByteArrayOutputStream out = new ByteArrayOutputStream(); | ||
System.setOut(new PrintStream(out)); | ||
|
||
MainKt.main(); | ||
|
||
final var actual = out.toString().trim(); | ||
|
||
Assertions.assertThat(actual).isEqualTo(expected); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
--- | ||
|
||
name: Коммутативная операция | ||
theory: | | ||
Мы все помним со школы: «от перемены мест слагаемых сумма не меняется». Это один из базовых и интуитивно понятных законов арифметики, он называется **коммутативным законом**. | ||
Бинарная операция считается коммутативной, если, поменяв местами операнды, вы получаете тот же самый результат. Очевидно, что сложение — коммутативная операция: *3 + 2 = 2 + 3*. А вот является ли коммутативной операция вычитания? Нет: *2 - 3 ≠ 3 - 2*. В программировании этот закон работает точно так же, как в арифметике. Более того, большинство операций, с которыми мы будем сталкиваться в реальной жизни, не являются коммутативными. Отсюда вывод: всегда обращайте внимание на порядок того, с чем работаете. | ||
instructions: | | ||
Это задание напрямую не связано с темой урока. Но будет полезным попрактиковаться с арифметическими операциями и выводом на экран. | ||
Напишите программу, которая считает и последовательно выводит на экран значения следующих математических выражений: «3 умножить на 5» и «-8 разделить на -4». | ||
<pre class='hexlet-basics-output'> | ||
15 | ||
2 | ||
</pre> | ||
# tips: [] | ||
|
||
definitions: | ||
- name: "Коммутативность" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
fun main() { | ||
// BEGIN | ||
println(8 / 2 + 5 - -3 / 2) | ||
// END | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
test: | ||
@ test.sh |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import java.io.ByteArrayOutputStream; | ||
import java.io.PrintStream; | ||
import org.assertj.core.api.Assertions; | ||
|
||
class Test { | ||
public static void main(final String[] args) { | ||
final var expected = "10"; | ||
|
||
MainKt.main(); | ||
|
||
ByteArrayOutputStream out = new ByteArrayOutputStream(); | ||
System.setOut(new PrintStream(out)); | ||
|
||
MainKt.main(); | ||
|
||
final var actual = out.toString().trim(); | ||
|
||
Assertions.assertThat(actual).isEqualTo(expected); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
--- | ||
|
||
name: Композиция операций | ||
theory: | | ||
А что, если понадобится вычислить такое выражение: *3 + 5 - 2*? Именно так мы и запишем: | ||
```kotlin | ||
println(3 + 5 - 2) // 3 + 5 - 2 => 8 - 2 => 6 | ||
``` | ||
Обратите внимание, что компьютер производит арифметические вычисления в правильном порядке: сначала деление и умножение, потом сложение и вычитание. Иногда этот порядок нужно изменить — об этом следующий урок. | ||
Или другой пример: | ||
```kotlin | ||
println(2 * 4 * 5 * 10) // 2 * 4 * 5 * 10 => 8 * 5 * 10 => 40 * 10 => 400 | ||
``` | ||
Как видно, операции можно соединять друг с другом, получая возможность вычислять все более сложные составные выражения. Чтобы представить себе то, как происходят вычисления внутри интерпретатора, давайте разберем пример: `2 * 4 * 5 * 10`. | ||
1. Сначала вычисляется *2 * 4* и получается выражение *8 * 5 * 10*. | ||
1. Затем *8 * 5*. В итоге имеем *40 * 10*. | ||
3. В конце концов происходит последнее умножение, и получается результат *400*. | ||
Операции можно соединять друг с другом, получая возможность вычислять все более сложные составные выражения. | ||
instructions: | | ||
Реализуйте программу, которая вычисляет значение выражения `8 / 2 + 5 - -3 / 2`. Не вычисляйте ничего самостоятельно, ваша программа должна производить все вычисления сама. | ||
<pre class='hexlet-basics-output'> | ||
10 | ||
</pre> | ||
Обратите внимание, что интерпретатор производит арифметические вычисления в правильном порядке: сначала деление и умножение, потом сложение и вычитание. Иногда этот порядок нужно изменить — об этом следующий урок. | ||
Также обратите внимание на то, что в Kotlin по умолчанию используется целочисленное деление, `3 / 2` будет `1`. | ||
# tips: [] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
fun main() { | ||
// BEGIN | ||
println(70 * (3 + 4) / (8 + 2)) | ||
// END | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
test: | ||
@ test.sh |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import java.io.ByteArrayOutputStream; | ||
import java.io.PrintStream; | ||
import org.assertj.core.api.Assertions; | ||
|
||
class Test { | ||
public static void main(final String[] args) { | ||
final var expected = "49"; | ||
|
||
MainKt.main(); | ||
|
||
ByteArrayOutputStream out = new ByteArrayOutputStream(); | ||
System.setOut(new PrintStream(out)); | ||
|
||
MainKt.main(); | ||
|
||
final var actual = out.toString().trim(); | ||
|
||
Assertions.assertThat(actual).isEqualTo(expected); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
--- | ||
|
||
name: Приоритет операций | ||
theory: | | ||
Посмотрите внимательно на выражение *2 + 2 * 2* и посчитайте в уме ответ. | ||
Правильный ответ: *6*. | ||
Если у вас получилось *8*, то этот урок для вас. В школьной математике мы изучали понятие «приоритет операции». Приоритет определяет то, в какой последовательности должны выполняться операции. Например, умножение и деление имеют больший приоритет, чем сложение и вычитание: *2 + 3 * 2* вычислится в *8*. | ||
Но нередко вычисления должны происходить в порядке, отличном от стандартного приоритета. В сложных ситуациях приоритет можно (и нужно) задавать круглыми скобками, точно так же, как в школе, например: `(2 + 2) * 2`. | ||
Скобки можно ставить вокруг любой операции. Они могут вкладываться друг в друга сколько угодно раз. Вот пара примеров: | ||
```kotlin | ||
println(3 * (4 - 2)) // => 6 | ||
println(7 * 3 + (4 / 2) - (8 + (2 - 1))) // => 14 | ||
``` | ||
Иногда выражение сложно воспринимать визуально. Тогда можно расставить скобки, не повлияв на приоритет. Например, задание из прошлого урока можно сделать немного понятнее, если расставить скобки. | ||
Было: | ||
```kotlin | ||
println(8 / 2 + 5 - -3 / 2) // => 10 | ||
``` | ||
Стало: | ||
```kotlin | ||
println(((8 / 2) + 5) - (-3 / 2)) // => 10 | ||
``` | ||
Запомните: код пишется для людей, потому что код будут читать люди, а машины будут только исполнять его. Для машин нет «более» понятного или «менее» понятного кода, независимо от того, является ли код корректным или нет. | ||
instructions: | | ||
Дано выражение `70 * 3 + 4 / 8 + 2`. | ||
Расставьте скобки так, чтобы оба сложения (`3 + 4` и `8 + 2`) высчитывались в первую очередь. Выведите результат на экран. | ||
# tips: [] |