Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Numbers#152

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
otmon76 merged 3 commits intojavascript-tutorial:masterfromotmon76:1.5.2
Jun 3, 2025
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions1-js/05-data-types/02-number/1-sum-interface/solution.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@


```js run demo
let a = +prompt("The first number?", "");
let b = +prompt("The second number?", "");
let a = +prompt("První číslo?", "");
let b = +prompt("Druhé číslo?", "");

alert( a + b );
```

Note the unary plus `+`before `prompt`. It immediately converts the value to a number.
Všimněte si unárního plus `+`před `prompt`, které okamžitě konvertuje hodnotu na číslo.

Otherwise,`a`and `b`would be string their sum would be their concatenation, that is: `"1" + "2" = "12"`.
Jinak by`a`a `b`byly řetězce a součtem by bylo jejich zřetězení, tedy: `"1" + "2" = "12"`.
6 changes: 3 additions & 3 deletions1-js/05-data-types/02-number/1-sum-interface/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,10 +2,10 @@ importance: 5

---

#Sum numbers from the visitor
#Sečtěte čísla od návštěvníka

Create a script that prompts the visitor to enter two numbers and then shows their sum.
Vytvořte skript, který vyzve návštěvníka, aby zadal dvě čísla, a pak zobrazí jejich součet.

[demo]

P.S.There is a gotcha with types.
P.S.Je tam chyták s typy.
18 changes: 9 additions & 9 deletions1-js/05-data-types/02-number/2-why-rounded-down/solution.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,33 @@
Internally the decimal fraction `6.35`is an endless binary. As always in such cases, it is stored with a precision loss.
Interně je desetinné číslo `6.35`nekonečné binární číslo. Jako vždy v takových případech je uloženo se ztrátou přesnosti.

Let's see:
Podívejme se:

```js run
alert( 6.35.toFixed(20) ); // 6.34999999999999964473
```

The precision loss can cause both increase and decrease of a number. In this particular case the number becomes a tiny bit less, that's why it rounded down.
Ztrátou přesnosti se číslo může zvýšit i snížit. V tomto konkrétním případě se číslo o něco málo sníží, proto bude zaokrouhleno dolů.

And what's for `1.35`?
A co `1.35`?

```js run
alert( 1.35.toFixed(20) ); // 1.35000000000000008882
```

Here the precision loss made the number a little bit greater, so it rounded up.
Zde ztráta přesnosti číslo trošičku zvýšila, takže se zaokrouhlilo nahoru.

**How can we fix the problem with`6.35`if we want it to be rounded the right way?**
**Jak můžeme problém s`6.35`vyřešit, chceme-li, aby se zaokrouhlilo správně?**

We should bring it closer to an integer prior to rounding:
Měli bychom je před zaokrouhlením přiblížit k celému číslu:

```js run
alert( (6.35 * 10).toFixed(20) ); // 63.50000000000000000000
```

Note that`63.5`has no precision loss at all. That's because the decimal part`0.5`is actually`1/2`.Fractions divided by powers of`2`are exactly represented in the binary system, now we can round it:
Všimněte si, že`63.5`nemá vůbec žádnou ztrátu přesnosti. Je to proto, že desetinná část`0.5`je ve skutečnosti`1/2`.Zlomky s mocninou`2`ve jmenovateli jsou v binární soustavě reprezentovány přesně, takže je nyní můžeme zaokrouhlit:


```js run
alert( Math.round(6.35 * 10) / 10 ); // 6.35 -> 63.5 -> 64(rounded) -> 6.4
alert( Math.round(6.35 * 10) / 10 ); // 6.35 -> 63.5 -> 64(zaokrouhleno) -> 6.4
```

10 changes: 5 additions & 5 deletions1-js/05-data-types/02-number/2-why-rounded-down/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,21 +2,21 @@ importance: 4

---

#Why 6.35.toFixed(1) == 6.3?
#Proč 6.35.toFixed(1) == 6.3?

According to the documentation`Math.round`and `toFixed`both round to the nearest number: `0..4`lead down while`5..9`lead up.
Podle dokumentace`Math.round`a `toFixed`zaokrouhlují obě na nejbližší číslo: `0..4`se zaokrouhluje dolů, zatímco`5..9`nahoru.

For instance:
Například:

```js run
alert( 1.35.toFixed(1) ); // 1.4
```

In the similar example below, why is `6.35`rounded to `6.3`, not `6.4`?
Proč se v podobném níže uvedeném příkladu `6.35`zaokrouhlí na `6.3` a ne na `6.4`?

```js run
alert( 6.35.toFixed(1) ); // 6.3
```

How to round`6.35`the right way?
Jak zaokrouhlit`6.35`správně?

View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@

functionreadNumber() {
letnum;
functionnačtiČíslo() {
letčíslo;

do {
num = prompt("Enter a number please?", 0);
} while ( !isFinite(num) );
číslo = prompt("Zadejte číslo, prosím:", 0);
} while ( !isFinite(číslo) );

if (num === null ||num === '') return null;
if (číslo === null ||číslo === '') return null;

return +num;
return +číslo;
}
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,33 +6,33 @@ afterEach(function() {
prompt.restore();
});

describe("readNumber", function() {
describe("načtiČíslo", function() {

it("if a number, returns it", function() {
it("je-li to číslo, vrátí je", function() {
prompt.returns("123");
assert.strictEqual(readNumber(), 123);
assert.strictEqual(načtiČíslo(), 123);
});

it("if0,returns it", function() {
it("je-li to0,vrátí ji", function() {
prompt.returns("0");
assert.strictEqual(readNumber(), 0);
assert.strictEqual(načtiČíslo(), 0);
});

it("continues the loop until meets a number", function() {
prompt.onCall(0).returns("not a number");
prompt.onCall(1).returns("not a number again");
it("pokračuje ve smyčce, dokud nenajde číslo", function() {
prompt.onCall(0).returns("to není číslo");
prompt.onCall(1).returns("to taky není číslo");
prompt.onCall(2).returns("1");
assert.strictEqual(readNumber(), 1);
assert.strictEqual(načtiČíslo(), 1);
});

it("if an empty line, returns null", function() {
it("je-li zadán prázdný řádek, vrátí null", function() {
prompt.returns("");
assert.isNull(readNumber());
assert.isNull(načtiČíslo());
});

it("if cancel, returns null", function() {
it("je-li stisknuto Storno, vrátí null", function() {
prompt.returns(null);
assert.isNull(readNumber());
assert.isNull(načtiČíslo());
});

});
20 changes: 10 additions & 10 deletions1-js/05-data-types/02-number/3-repeat-until-number/solution.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,23 @@

```js run demo
functionreadNumber() {
letnum;
functionnačtiČíslo() {
letčíslo;

do {
num = prompt("Enter a number please?", 0);
} while ( !isFinite(num) );
číslo = prompt("Zadejte číslo, prosím:", 0);
} while ( !isFinite(číslo) );

if (num === null ||num === '') return null;
if (číslo === null ||číslo === '') return null;

return +num;
return +číslo;
}

alert(`Read: ${readNumber()}`);
alert(`Načteno: ${načtiČíslo()}`);
```

The solution is a little bit more intricate that it could be because we need to handle`null`/empty lines.
Řešení je trochu složitější, než by mohlo být, protože si musíme poradit s`null`/prázdnými řádky.

So we actually accept the input until it is a "regular number". Both`null` (cancel) and empty line also fit that condition, because in numeric form they are `0`.
Ve skutečnosti tedy přijímáme vstup tak dlouho, dokud to není „skutečné číslo“. Tuto podmínku splňují i`null` (storno) a prázdný řádek, protože v číselné podobě jsou obě `0`.

After we stopped, we need to treat`null`and empty line specially (return `null`),because converting them to a number would return `0`.
Po skončení musíme zacházet s`null`a s prázdným řádkem speciálně (vrátit `null`),jelikož jejich konverze na číslo by vrátila `0`.

View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,13 +2,13 @@ importance: 5

---

#Repeat until the input is a number
#Opakování, dokud na vstupu nebude číslo

Create a function `readNumber` which prompts for a number until the visitor enters a valid numeric value.
Vytvořte funkci `načtiČíslo`, která se bude ptát na číslo tak dlouho, až návštěvník zadá platnou číselnou hodnotu.

The resulting value must be returned as a number.
Výslednou hodnotu funkce musí vrátit jako číslo.

The visitor can also stop the process by entering an empty line or pressing "CANCEL". In that case, the function should return `null`.
Návštěvník může tento proces ukončit i zadáním prázdného řádku nebo stisknutím „Storno“. V takovém případě by funkce měla vrátit `null`.

[demo]

View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
That's because`i`would never equal `10`.
Protože`i`nikdy nebude rovno `10`.

Run it to see the *real* values of `i`:
Spusťme si jej, abychom viděli *skutečné* hodnoty `i`:

```js run
let i = 0;
Expand All@@ -10,8 +10,8 @@ while (i < 11) {
}
```

None of them is exactly `10`.
Žádná z nich není přesně `10`.

Such things happen because of the precision losses when adding fractions like `0.2`.
Takové věci se dějí kvůli ztrátám přesnosti při přičítání desetinných čísel jako `0.2`.

Conclusion: evade equality checks when working with decimal fractions.
Důsledek: když pracujete s desetinnými čísly, vyvarujte se testů rovnosti.
4 changes: 2 additions & 2 deletions1-js/05-data-types/02-number/4-endless-loop-error/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,9 +2,9 @@ importance: 4

---

#An occasional infinite loop
#Občasná nekonečná smyčka

This loop is infinite. It never ends. Why?
Tento cyklus je nekonečný. Nikdy neskončí. Proč?

```js
let i = 0;
Expand Down
10 changes: 5 additions & 5 deletions1-js/05-data-types/02-number/8-random-min-max/solution.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
We need to "map" all values from the interval0..1into values from `min`to `max`.
Musíme „namapovat“ všechny hodnoty z intervalu0..1na hodnoty od `min`do `max`.

That can be done in two stages:
To můžeme udělat ve dvou krocích:

1.If we multiply a random number from0..1by `max-min`,then the intervalof possible values increases `0..1`to `0..max-min`.
2.Now if we add`min`,the possibleintervalbecomes from`min`to `max`.
1.Když vynásobíme náhodné číslo z0..1číslem `max-min`,pak se intervalmožných hodnot zvětší z `0..1`na `0..max-min`.
2.Když nyní přičteme`min`,možnýintervalse změní na interval od`min`do `max`.

The function:
Funkce:

```js run
function random(min, max) {
Expand Down
8 changes: 4 additions & 4 deletions1-js/05-data-types/02-number/8-random-min-max/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,13 +2,13 @@ importance: 2

---

#A random number fromminto max
#Náhodné číslo odmindo max

The built-in function`Math.random()`creates a random value from`0`to `1` (not including `1`).
Vestavěná funkce`Math.random()`vytváří náhodnou hodnotu od`0`do `1` (kromě `1`).

Write the function`random(min, max)` to generate a random floating-point number from`min`to `max` (not including `max`).
Napište funkci`random(min, max)`, která bude generovat náhodné číslo s pohyblivou řádovou čárkou od`min`do `max` (kromě `max`).

Examples of its work:
Příklady, jak má fungovat:

```js
alert( random(1, 5) ); // 1.2345623452
Expand Down
50 changes: 25 additions & 25 deletions1-js/05-data-types/02-number/9-random-int-min-max/solution.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,66 +1,66 @@
#The simple but wrong solution
#Jednoduché, ale nesprávné řešení

The simplest, but wrong solution would be to generate a value from`min`to `max`and round it:
Jednoduchým, ale nesprávným řešením by bylo generovat hodnotu od`min`do `max`a zaokrouhlit ji:

```js run
function randomInteger(min, max) {
letrand = min + Math.random() * (max - min);
return Math.round(rand);
letnáhodnéČíslo = min + Math.random() * (max - min);
return Math.round(náhodnéČíslo);
}

alert( randomInteger(1, 3) );
```

The function works, but it is incorrect. The probability to get edge values`min`and `max` is two times less than any other.
Tato funkce funguje, ale nekorektně. Pravděpodobnost, že získáme krajní hodnoty`min`a `max`, je dvakrát nižší, než u ostatních hodnot.

If you run the example above many times, you would easily see that`2` appears the most often.
Jestliže si spustíte výše uvedený příklad mnohokrát po sobě, brzy uvidíte, že nejčastěji se objevuje`2`.

That happens because`Math.round()`gets random numbers from the interval`1..3`and rounds them as follows:
Děje se to proto, že`Math.round()`získává náhodná čísla z intervalu`1..3`a zaokrouhluje je následovně:

```js no-beautify
values from 1 ...to 1.4999999999become 1
values from 1.5 ...to 2.4999999999become 2
values from 2.5 ...to 2.9999999999become 3
hodnoty od 1 ...do 1.4999999999se zaokrouhlí na 1
hodnoty od 1.5 ...do 2.4999999999se zaokrouhlí na 2
hodnoty od 2.5 ...do 2.9999999999se zaokrouhlí na 3
```

Now we can clearly see that`1`gets twice less values than `2`.And the same with `3`.
Nyní jasně vidíme, že`1`má dvakrát méně hodnot než `2`.Totéž platí pro `3`.

#The correct solution
#Správné řešení

There are many correct solutions to the task. One of them is to adjust interval borders. To ensure the same intervals, we can generate values from`0.5 to3.5`, thus adding the required probabilities to the edges:
Tato úloha má mnoho správných řešení. Jedno z nich je přizpůsobit hranice intervalu. Abychom zajistili stejné intervaly, můžeme generovat hodnoty od`0.5` do `3.5` a tím zvýšit požadované pravděpodobnosti krajních hodnot:

```js run
*!*
function randomInteger(min, max) {
//now rand is from(min-0.5)to (max+0.5)
letrand = min - 0.5 + Math.random() * (max - min + 1);
return Math.round(rand);
//nyní náhodnéČíslo je od(min-0.5)do (max+0.5)
letnáhodnéČíslo = min - 0.5 + Math.random() * (max - min + 1);
return Math.round(náhodnéČíslo);
}
*/!*

alert( randomInteger(1, 3) );
```

An alternative way could be to use`Math.floor`for a random number from`min`to `max+1`:
Alternativním způsobem by bylo použít`Math.floor`pro náhodné číslo od`min`do `max+1`:

```js run
*!*
function randomInteger(min, max) {
//here rand is from minto (max+1)
letrand = min + Math.random() * (max + 1 - min);
return Math.floor(rand);
//zde náhodnéČíslo je od mindo (max+1)
letnáhodnéČíslo = min + Math.random() * (max + 1 - min);
return Math.floor(náhodnéČíslo);
}
*/!*

alert( randomInteger(1, 3) );
```

Now all intervals are mapped this way:
Nyní jsou všechny intervaly mapovány tímto způsobem:

```js no-beautify
values from 1 ...to 1.9999999999become 1
values from 2 ...to 2.9999999999become 2
values from 3 ...to 3.9999999999become 3
hodnoty od 1 ...do 1.9999999999se zaokrouhlí na 1
hodnoty od 2 ...do 2.9999999999se zaokrouhlí na 2
hodnoty od 3 ...do 3.9999999999se zaokrouhlí na 3
```

All intervals have the same length, making the final distribution uniform.
Všechny intervaly mají stejnou délku, takže konečné rozložení je rovnoměrné.
Loading

[8]ページ先頭

©2009-2025 Movatter.jp