Operators: Arithmetic
● Beginner3 min
+ - * / work as in school; % is the remainder and ** the power.
fn main() {
print(7 + 2)
print(7 - 2)
print(7 * 2)
print(7 / 2)
print(7 % 2)
print(2 ** 10)
print(7.0 / 2.0)
}The compiler warned, then the program ran:
kavach run arithmetic.kav
warning: `7 / 2` is `3`: whole numbers divide to a whole number. Write `7.0 / 2.0` for a fraction, or `7.div_floor(2)` when the whole part is meant (spec 1.8)95143110243.5
- Two
Ints divide to anInt:7 / 2is3. Use floats,7.0 / 2.0, for3.5. - Written with two numbers that don't divide evenly, as
7 / 2is here, it also gets a warning: it rarely means what it says. Write7.div_floor(2)when the whole part is what you want. 2 ** 10is 2 to the power 10.- A whole-number result too big for its type stops the program; it never wraps to a wrong number.
Negative numbers: two ways to divide
fn main() {
print(-7 / 2)
print((-7).div_floor(2))
print(-7 % 3)
print((-7).mod(3))
const today = 1
print((today - 3).mod(7))
}The compiler warned, then the program ran:
kavach run floor.kav
warning: `-7 / 2` is `-3`: whole numbers divide to a whole number. Write `-7.0 / 2.0` for a fraction, or `(-7).div_floor(2)` when the whole part is meant (spec 1.8)-3-4-125
/and%round toward zero, as C and Java do:-7 / 2is-3, and-7 % 3is-1.div_floorrounds down, andmodgives a remainder with the sign of the number you divide by, as Python's//and%do:-4and2.- Use
modfor anything that wraps around, such as days of the week: 3 days before day 1 is day5, never-2.
What Kavach does for you
Overflow is caught, never wrapped
An integer that goes past its type's limit stops the program with a clear message, instead of quietly turning into a wrong number. When the compiler knows the values, even through a loop over known numbers, it is a compile error.