Step 1 of 5 · Reading · ~3 min
Learn
Getting Started
Numbers and Math
Arithmetic looks the same in every language until the edge cases bite. Go's edges are unusually well-defined — no undefined behavior, no silent coercions — but you have to know where they are, because two of them (integer division and float representation) fail quietly.
Integer arithmetic: exact, until it isn't
+ - * / % behave as expected on int, with one universal gotcha:
Integer division truncates — it doesn't round. 99 / 100 is 0, and a surprising number of real bugs ("why is my percentage always zero?") are exactly that line. When you want real division on integer variables, convert deliberately: float64(a) / float64(b).
% (modulo) is the remainder — the tool for "is it divisible" (n % 3 == 0), "wrap around" (i % len), and digit extraction (n % 10 is the last digit, n / 10 drops it). It earns its keep constantly.
Overflow: Go integers are fixed-size and wrap around silently at runtime — a runtime int64 holding math.MaxInt64, plus one, becomes a huge negative number with no exception and no warning. (Written as the compile-time constant math.MaxInt64 + 1 the compiler actually rejects it — "constant overflows int64" — so silent wraparound is strictly a runtime-value behavior.) With 64 bits (±9.2 quintillion) you won't hit it counting things; you will hit it multiplying big numbers. Know it exists.
Floats: fast, useful, and slightly wrong
float64 is IEEE-754 double precision — the same type every mainstream language uses — and it cannot represent most decimal fractions exactly:
This isn't a Go bug; it's binary floating point being binary. Two working rules: never compare floats with == (compare math.Abs(a-b) < 1e-9 instead), and never use floats for money (count cents in an int).
Conversions are always loud
As with all Go types, nothing converts itself:
int(f) chopping toward zero is the second silent killer of the lesson. Rounding is explicit: math.Round(f) (then convert).
The math package
Everything in math speaks float64 — mixing it with int variables means conversions at the border, written out where everyone can see them.
Your exercise
Rectangle area is one multiplication — which is exactly why it's here. The actual skill being graded is the plumbing: read values from stdin (fmt.Scan(&w, &h)), compute, and print in the exact expected format. Decide consciously whether the inputs are int or float64 (read the problem's examples!), because 12 and 12.00 are different outputs, and the grader compares the characters you printed. Getting input → types → arithmetic → formatted output right on a trivial formula is the loop you'll run on every non-trivial one for the rest of the course.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…