Числа с плавающей точкой: f32 и f64
Работайте с дробными числами.
«Числа с плавающей точкой: f32 и f64» — бесплатный урок Zig Academy на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Zig Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Zig Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Numbers with a Fraction
When you need decimals, Zig offers floating-point types. They store fractional values like 3.14 instead of whole numbers only.
f64 Is the Common Choice
The f64 type holds a double-precision float using 64 bits. It is the usual default when you want accuracy and plenty of range.
const pi: f64 = 3.14159;f32 Trades Precision for Size
An f32 uses 32 bits. It saves memory and can be faster, but it stores fewer significant digits than an f64.
const ratio: f32 = 0.5;Zig Has More Float Widths
Beyond f32 and f64, Zig also supports f16 and f128. You choose the width that balances precision against memory and speed.
Float Literals Need a Dot
A float literal includes a decimal point, like 2.0. Writing just 2 gives an integer, which is a different kind of value.
const half = 0.5;
const one = 1.0;Scientific Notation Works Too
You can write very large or small floats with an exponent. The form 1.5e3 means 1.5 times ten to the third power, or 1500.
const big: f64 = 1.5e3;Doing Float Math
The usual operators apply to floats. Division of two floats keeps the fractional part instead of throwing it away.
const result: f64 = 7.0 / 2.0; // 3.5Floats Are Approximate
Floats cannot store every decimal exactly. Tiny rounding errors mean 0.1 plus 0.2 may not equal exactly 0.3.
Compare with a Tolerance
Because of rounding, avoid testing floats for exact equality. Check that the difference is smaller than a tiny threshold instead.
const close = @abs(a - b) < 0.0001;Convert Int to Float
To turn an integer into a float you ask explicitly with @floatFromInt. Zig never mixes the two number kinds silently.
const n: i32 = 10;
const f: f64 = @floatFromInt(n);Special Float Values
Floats can also represent infinity and not-a-number. These appear from operations like dividing by zero, and the std library names them.
Quick Check
You divide one float by another and want to keep the fractional result. What is true about floating-point math in Zig?
Recap
Use f64 for general decimals and f32 to save space. Remember floats are approximate, so compare with a tolerance and cast on purpose. 🎯
Часто задаваемые вопросы
Урок «Числа с плавающей точкой: f32 и f64» бесплатный?
Да — полный текст урока «Числа с плавающей точкой: f32 и f64» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Zig Academy, подпишись на CoddyKit PRO. Курс Zig Academy содержит 4 уроков всего.
Чему я научусь в уроке «Числа с плавающей точкой: f32 и f64»?
Работайте с дробными числами. Ты практикуешь Zig Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Zig Academy?
Предыдущий опыт не требуется. Zig Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.
Сколько времени занимает урок «Числа с плавающей точкой: f32 и f64»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Zig Academy?
Да. Каждый урок Zig Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Целые числа заданного размера: i32, u8, usize
- Числа с плавающей точкой: f32 и f64
- bool, void и типы времени компиляции
- Числовые литералы и символы подчёркивания