Learn/F#/3. Reading input and arithmetic
Lesson 3 of 8
Sign in

F#, lesson 3

Reading input and arithmetic

A program gets much more interesting when it reacts to data. The simplest source of data is standard input (stdin): the text a user types or, here, the text the tests supply.

Reading a line

stdin.ReadLine() reads one line and returns it as a string, without the new line at the end. Each call reads the next line.

stdin is the .NET console input stream, and ReadLine() is a .NET method, which is why it uses parentheses and a dot. If there is no more input, ReadLine() returns null.

Text to numbers

Input always arrives as text. Convert it with the conversion functions:

int "42" gives 42, and gives . If the text is not a number, the program stops with an exception. Use to remove stray spaces before converting: .

2 exercises to try what you just read.

Exercise 1

Pizza party

Press Ctrl Enter or Check to test your code.

Exercise 2

Temperature converter

Press Ctrl Enter or Check to test your code.

float "1.75"
1.75
.Trim()
int (line.Trim())

You will often see the pipe operator |>. x |> f means f x, so a chain of steps reads from left to right:

Arithmetic

F# uses the familiar operators: +, -, *, / and % (remainder). The same operators work for int and float, but both sides must have the same type.

With integers, / throws away the fractional part:

With floats, you get the exact result, and ** raises to a power:

Float literals need a decimal point: write 9.0, not 9, when the other side is a float. Mixing is an error, so convert one side when needed: float 3 * 1.5.

*, / and % bind tighter than + and -, as in maths. Parentheses make your intent clear when in doubt.

Rounding when printing

%.1f prints a float rounded to one decimal place, %.2f to two. The value itself is not changed; only the printed text is rounded. If you need a rounded value, use round, floor or ceil, which all return floats.

Further reading

  • Arithmetic operators
  • Casting and conversions

Every pizza has 8 slices. Read the number of people (first line) and the number of pizzas (second line). Share the slices equally, then print how many whole slices each person gets and how many are left over. There is always at least one person.

Sample input:

Sample output:

Read a temperature in degrees Celsius (it may have a decimal part) and print it in Fahrenheit, rounded to one decimal place. The formula is F = C * 9 / 5 + 32.

Sample input:

Sample output:

let name = stdin.ReadLine()
printfn "Hi, %s!" name
let age = int (stdin.ReadLine())
let height = float (stdin.ReadLine())
printfn "%d %.2f" (age + 1) (height * 100.0)
let count = stdin.ReadLine().Trim() |> int
printfn "%d %d" (17 / 5) (17 % 5)       // 3 2
let km = 42.195
printfn "%.1f miles" (km / 1.609)       // 26.2 miles
printfn "%.0f" (2.0 ** 10.0)            // 1024
5
3
Slices each: 4
Left over: 4
36.6
97.9