Tin

Examples · 17 of 339

17-numbers

Numbers never wrap around silently.

examples/17-numbers.tintin run examples/17-numbers.tin
// Numbers never wrap around silently.
//
// `int` is 32-bit, from -2147483648 to 2147483647. `+ - *` are checked:
// overflow is a compile error when the compiler can see it, and a panic at run
// time otherwise, never a wrong answer. Literals that don't fit are compile
// errors too: `2147483648`, `0xFFFF_FFFF`.

fn checkedSum(xs: int[]): int {
  var total = 0
  for x in xs { total += x }
  total
}

fn main() {
  let smallest = -2147483648
  let largest = 0x7fff_ffff
  print("{smallest} .. {largest}")
  print(checkedSum([1_000_000, 2_000_000, 3_000_000]))
  print(largest / 2 * 2 + 1 == largest)

  // between int and float, conversions are explicit
  let ratio = float(largest) / 1e9
  print(ratio.fixed(3))
  print(int(ratio * 100.0))
}
-2147483648 .. 2147483647
6000000
true
2.147
214