Chuyển đến nội dung

Bài 5 · Basics and Types

Numbers: Integers and Floats

Learn Nim's integer and float types, literals, div and mod versus slash, shifts, overflow checking, the math module and rounding, with runnable C stand-ins.

Numbers are the first built-in types you meet. Nim has a family of integer types of different sizes, and two floating-point types. The rules are simple, but they have a few surprises if you come from Python or JavaScript: integer division has its own operator, and overflow is a real thing the compiler can catch for you.

The Nim snippets are read-only (no Nim compiler here). The C blocks are runnable stand-ins for the same arithmetic.

Integer types

Type Size Range
int pointer size (64 bits on most machines) about -9.2e18 to 9.2e18
int8, int16, int32, int64 8/16/32/64 bits signed
uint, uint8 (byte), uint16, uint32, uint64 unsigned 0 up to 2^n - 1

int is the default and the right choice for counts, indexes and general arithmetic. Pick a sized type when you care about layout (file formats, protocols, large arrays of small numbers). Use high(int8) and low(int8) to ask for the limits:

NIM
echo high(int8)      # 127
echo low(int8)       # -128
echo high(uint8)     # 255

Literals

NIM
let a = 1_000_000        # underscores make big numbers readable
let b = 0xFF             # hexadecimal, 255
let c = 0b1011           # binary, 11
let d = 0o17             # octal, 15
let e = 255'u8           # typed literal: a uint8
let f = 42'i64           # an int64

A literal without a suffix is an int (if it fits) and can be implicitly used where a smaller integer type is expected, as long as the value fits.

Arithmetic operators

Operator Meaning Example Result
+ - * add, subtract, multiply 6 * 7 42
div integer division, truncating toward zero 17 div 5 3
mod remainder (sign follows the left side) 17 mod 5 2
/ float division, always 17 / 5 3.4
shl, shr shift left / right 1 shl 4 16
ashr arithmetic shift right (keeps sign) -8 ashr 1 -4
and, or, xor, not bitwise on integers 6 and 3 2

The surprise for newcomers: the slash / on two integers returns a float. Use div when you want the integer quotient:

NIM
echo 7 div 2        # 3
echo 7 / 2          # 3.5
echo -7 div 2       # -3  (truncates toward zero)
echo -7 mod 2       # -1

and, or and not are the same words used for booleans; Nim picks bitwise or logical behavior from the operand types.

Overflow

What happens when a number does not fit?

NIM
var small: int8 = 127
small += 1          # in a debug build: raises OverflowDefect

In a normal (debug) build Nim inserts checks: arithmetic that overflows raises an OverflowDefect, and a bad conversion raises RangeDefect. With -d:release the checks stay; with -d:danger they are removed and the result wraps around. Checks catch real bugs, so keep them until you have measured a performance need.

Floating point

float is a 64-bit double (the same as float64), and float32 is the smaller one. Literals contain a dot or an exponent:

NIM
let g = 9.81
let h = 6.02e23
let i = 1.5'f32

Arithmetic follows IEEE 754, so 0.1 + 0.2 is not exactly 0.3, and dividing a float by zero gives infinity instead of an error:

NIM
import std/math
echo sqrt(16.0)        # 4.0
echo 2.0 ^ 10          # 1024.0   (^ is power in std/math)
echo floor(3.7)        # 3.0
echo ceil(3.2)         # 4.0
echo round(2.5)        # 3.0
echo 1.0 / 0.0         # inf

The math module also offers sin, cos, ln, log10, pow, abs, min, max, PI and trunc. To compare floats, never test equality directly; use a tolerance with almostEqual:

NIM
import std/math
echo almostEqual(0.1 + 0.2, 0.3)   # true

Mixing integers and floats

Nim does not silently convert between the two. Convert explicitly:

NIM
let count = 7
let average = count.float / 2      # float(count) / 2
let whole = int(3.9)               # 3, truncates

More on conversions in the conversion lesson.

Stand-in: division, remainder and overflow in C

C's / on integers behaves like Nim's div, and % behaves like mod. This stand-in shows both, and detects overflow with a GCC/Clang builtin, which is roughly what Nim's debug checks do.

C Stand-in: div, mod and overflow detection

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Notice that -7 / 2 is -3 in C, matching Nim's -7 div 2, and -7 % 2 is -1, matching mod.

Stand-in: bit shifts

Shifts are the building blocks of masks and flags. Here is the same logic as Nim's shl, shr, and, or and xor.

C Stand-in: shifts and masks

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does 17 / 5 give in Nim?

    The slash operator always does float division. Use 17 div 5 for the integer quotient 3.
  2. 2. What is -7 mod 2 in Nim?

    mod keeps the sign of the left operand, like C's %, so the result is -1.
  3. 3. In a default debug build, what happens when an int8 goes past 127?

    Nim inserts overflow checks in debug and release builds; only -d:danger removes them.
  4. 4. Which is the safest way to compare 0.1 + 0.2 with 0.3?

    Floating-point sums carry rounding error; compare with a tolerance.

Summary

  • int is the default integer; sized types (int8 ... uint64) are for layout and ranges.
  • div and mod are integer operators; / always yields a float.
  • Overflow raises OverflowDefect unless you build with -d:danger.
  • float is a 64-bit double; use std/math for functions and almostEqual for comparisons.
  • Number literals support underscores, hex, binary, octal and type suffixes.

Next: Booleans, characters and operators

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.