Drills — numbers and conversion
Types and conversions have to be written, not just read. Five drills, easy to harder. Write each function, call it from main on the examples, and compare with the solution. Watch the / in the first two especially — one of them hides the exact trap from the last step.
1 (easy) — percent. What fraction of whole is part, as a percentage?
percent(190, 380) → 50.0 percent(1, 4) → 25.0
func percent(part, whole int) float64 {
return float64(part) / float64(whole) * 100
}
Try it without the float64(...) and you get 0.0 — 190 / 380 in int world is 0. The conversion isn't decoration; it's the difference between right and silently wrong.
2 (easy) — average. The mean of three integers, as a float64.
average(3, 4, 5) → 4.0 average(1, 2, 2) → 1.7
func average(a, b, c int) float64 {
return float64(a+b+c) / 3
}
Same trap, same cure: convert to float64 before the division. float64((a+b+c)/3) would divide in int first and lose the decimals — too late.
3 (medium) — toInt. Turn text into a number, but never crash: return (value, ok). This is the core of lesson 5's readInt.
toInt("42") → 42, true toInt("x") → 0, false
func toInt(s string) (int, bool) {
n, err := strconv.Atoi(s)
if err != nil {
return 0, false
}
return n, true
}
4 (medium) — validNumber. Parse and bounds-check: the text must be a number and fall within lo..hi.
validNumber("50", 1, 380) → 50, true validNumber("900", 1, 380) → 0, false
func validNumber(s string, lo, hi int) (int, bool) {
n, err := strconv.Atoi(s)
if err != nil || n < lo || n > hi {
return 0, false
}
return n, true
}
"It's a number" and "it's a valid number" are two different checks — 900 pages in a 380-page book parses fine and is still wrong.
5 (harder) — progressPercent. The percentage read, but guard the empty book: dividing by 0 here gives you +Inf or NaN, not a crash — a wrong answer that spreads silently. Return 0 when there's nothing to divide by.
progressPercent(190, 380) → 50.0 progressPercent(1, 0) → 0.0
func progressPercent(read, total int) float64 {
if total <= 0 {
return 0
}
return float64(read) / float64(total) * 100
}
Tip. Every one of these is a pure function — text or numbers in, a value out — and every one is a place a
/or anAtoicould hide a silent bug. That makes them idealgo testtargets in lesson 13. Run each against the examples now.