Pular para o conteúdo

Aritmética

Nesta página

Os operadores aritméticos básicos (+, -, *, /, %) funcionam para inteiros e floats. A divisão / sempre retorna float quando pelo menos um operando é float; % devolve o resto. O operador ** é a exponenciação e é associativo à direita2 ** 3 ** 2 é calculado como 2 ** (3 ** 2).

Aritmética básica, potenciação, negação unária e atribuição composta (+=, -=, *=, /=, %=).

01-arithmetic.zolo
Playground
// Feature: Arithmetic operators

// Syntax: `+`, `-`, `*`, `/`, `%`, `**` (power), `-x` (unary)

// When to use: basic numeric calculations. `**` is right-assoc;

// `/` follows the type rule (int/int -> float in Zolo, but the

// result interpolates normally).


// Add, subtract, multiply.

print(10 + 3)  // 13

print(10 - 3)  // 7

print(10 * 3)  // 30


// Division and modulo.

print(10 / 3)  // 3.333...

print(10 % 3)  // 1

print(20 % 7)  // 6


// Power (right-associative): 2 ** 3 ** 2 = 2 ** 9 = 512.

print(2 ** 10)  // 1024

print(2 ** 3 ** 2)  // 512


// Unary negation.

let x = 5
print(-x)  // -5

print(--x)  // 5


// Floats.

print(1.5 + 2.5)  // 4.0

print(0.1 + 0.2)  // 0.30000000000000004 (IEEE-754)


// Compound assignment — `op=` for mutables.

var total = 100
total += 25
total -= 10
total *= 2
total /= 5
total %= 17
print(total)  // (((100+25-10)*2)/5)%17 = 46%17 = 12

Para divisão que arredonda em direção a −∞ — como // em Python ou Lua — o Zolo usa ~/ (floor division). O resultado é int quando ambos os operandos são inteiros; float quando há float. O operador composto é ~/=.

~/ divide e arredonda para baixo; ~/= é a forma de atribuição composta.

11-floor-division.zolo
Playground
// Feature: Floor division operator `~/` (and compound `~/=`)

// Syntax: `a ~/ b` — integer/floor division (Lua `//` semantics)

// When to use: integer-preserving division that rounds toward −∞.

//   int ~/ int  → int  (floor toward −∞)

//   float ~/ *  → float  (floor of the quotient)

//   int ~/ 0    → runtime error

// Note: `~/` does NOT conflict with the `//` line-comment token.


// Basic integer floor division.

print(7 ~/ 2)    // 3

print(-7 ~/ 2)   // -4  (floor toward −∞, not −3)

print(7 ~/ -2)   // -4

print(-7 ~/ -2)  // 3


// Float operand — result is float (floored quotient).

print(7.5 ~/ 2)  // 3

print(7.0 ~/ 2)  // 3


// Compound assignment ~/=

var x = 20
x ~/= 6
print(x)  // 3


// Negative compound assignment.

var y = -20
y ~/= 6
print(y)  // -4

Desafio

Com var x = 17, aplique x ~/= 5 e verifique o resultado. Depois repita com x = -17 — note que o arredondamento vai em direção a −∞, não a zero.

Buscar no Zolo

9 resultados

enespt-br