Today we learn operators and do some exercises
Operators
Operators are special symbols that perform operations on one or more operands (values or variables)
operator for 2 variables:
like +: 1 + 1 = 2, the '+' here is operator, it add the left number 1 and right number 1
we introduce 6 operators
- +
let num0 = 1
let num1 = 1
let sum = num0 + num1
printfn "1 + 1 = %i" sum // output: 1 + 1 = 2
- -
let num0 = 2
let num1 = 1
let difference = num0 - num1
printfn "2 - 1 = %i" difference // output: 2 - 1 = 1
- /
let num0 = 4
let num1 = 2
let quotient = num0 / num1
printfn "4 / 2 = %i" quotient // output: 4 / 2 = 2
- %
let num0 = 3
let num1 = 2
let remainder = num0 % num1
printfn "3 %% 2 = %i" remainder // output: 3 % 2 = 1
- <>
let num0 = 3
let num1 = 2
let equal = num0 <> num1
printfn "is 3 not equals 2? %b" equal // output: is 3 not equals 2? true
- =
let num0 = 3
let num1 = 2
let equal = num0 = num1
printfn "is 3 equals 2? %b" equal // output: is 3 equals 2? false
exercises
- 1 + 2 * 3 = ?
- (1 + 2) * 3 = ?
- 2 + 2 = 2 * 2?
- there are 20 apples for lunch, 10 students in the class, how many apples one student can get?
- there are 21 apples for lunch, 10 students in the class, how many apples left?
answers
- '*' has higher priority than +
let results = 1 + 2 * 3
printfn "1 + 2 * 3 = %i" results // output: 1 + 2 * 3 = 7
- () changed the priority, + inside has higher priority than *
let results = (1 + 2) * 3
printfn "(1 + 2) * 3 = %i" results // output: (1 + 2) * 9
- = can compare expression, the right = has higher priority than left =, which asign value of results
let results = 2 + 2 = 2 * 2
printfn "2 + 2 = 2 * 2 is %b" results // output: 2 + 2 = 2 * 2 is true
4.
let number_of_apples = 20
let number_of_students = 10
let apples_of_each_student = number_of_apples / number_of_students
printfn "every student can get %i apple" apples_of_each_student // output: every student can get 2 apple
5.
let number_of_apples = 21
let number_of_students = 10
let apples_left = number_of_apples % number_of_students
printfn "%i apple left after distributing" apples_left // output: 1 apple left after distributing
Top comments (0)