← thecodex.expert · The Codex Family of Knowledge
Tier 0 · Absolute Beginner · Go Project

Temperature Converter

Convert temperatures between Celsius and Fahrenheit. You will learn how a program takes a number, applies a formula, and gives back a result — the essence of almost every useful tool.

🧠 Teaches how to think spoonfed, every age Last verified:

1 The Problem

We want a small program that converts a temperature from Celsius to Fahrenheit, or the other way around. The user picks which direction, types a number, and the program does the maths and shows the answer. Simple — but it teaches the core shape of every calculator-style tool: ask, calculate, show.

Where this shows up in real life: every app that takes a number and transforms it — a currency converter, a tip calculator, a unit converter, a tax estimator — is doing exactly this. Take input, apply a formula, return a result. Master the pattern here and you can build any of them.

2 How to Think About It

Before any code, think about the two things the program needs to know and the two formulas it might use. You do not need Go yet — just the plan:

The plan — in plain English
1. Ask the user which way to convert (Celsius→Fahrenheit, or the reverse). → 2. Ask for the temperature number. → 3. Apply the right formula (C→F is ×9/5 then +32; F→C is −32 then ×5/9). → 4. Show the answer. The only “hard” part is remembering the two formulas — and the program remembers them for you.

1

2

Ask: convert which way?

Choice 1 or 2?

Read Celsius

Read Fahrenheit

Multiply by 9/5, add 32

Subtract 32, multiply by 5/9

Show Fahrenheit

Show Celsius

3 The Build — explained part by part

Here is the complete converter. Read each part’s note below — you should understand the whole thing from the notes alone.

Goconverter.go
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

// cToF converts Celsius to Fahrenheit.
func cToF(celsius float64) float64 {
	return celsius*9/5 + 32
}

// fToC converts Fahrenheit to Celsius.
func fToC(fahrenheit float64) float64 {
	return (fahrenheit - 32) * 5 / 9
}

func main() {
	reader := bufio.NewReader(os.Stdin)

	fmt.Println("Temperature Converter")
	fmt.Println("1. Celsius to Fahrenheit")
	fmt.Println("2. Fahrenheit to Celsius")
	fmt.Print("Choose 1 or 2: ")

	choiceLine, _ := reader.ReadString('\n')
	choice := strings.TrimSpace(choiceLine)

	switch choice {
	case "1":
		fmt.Print("Enter temperature in Celsius: ")
		line, _ := reader.ReadString('\n')
		celsius, err := strconv.ParseFloat(strings.TrimSpace(line), 64)
		if err != nil {
			fmt.Println("Please type a number.")
			return
		}
		fmt.Printf("%.1f°C is %.1f°F\n", celsius, cToF(celsius))
	case "2":
		fmt.Print("Enter temperature in Fahrenheit: ")
		line, _ := reader.ReadString('\n')
		fahrenheit, err := strconv.ParseFloat(strings.TrimSpace(line), 64)
		if err != nil {
			fmt.Println("Please type a number.")
			return
		}
		fmt.Printf("%.1f°F is %.1f°C\n", fahrenheit, fToC(fahrenheit))
	default:
		fmt.Println("Please choose 1 or 2.")
	}
}
⚠ No in-browser playground here
Go compiles to a real binary, so unlike the Python version of this project there is no editor above you can run in the browser. Copy the code below and run it on your own machine — it takes seconds once Go is installed.
What each part does — in plain words
func cToF / func fToC — we pull each formula into its own small function. This is good practice in any language: it names the idea, and (as you will see below) makes it directly testable.

switch choice { case "1": ... } — Go’s switch is the natural way to branch on several exact values. It plays the same role as Python’s if / elif / else chain, but reads more like a menu.

strconv.ParseFloat(strings.TrimSpace(line), 64) — turn the typed text into a decimal number. We use ParseFloat (not Atoi) because temperatures can have decimals like 36.6; the 64 means “give me a 64-bit float”, Go’s standard precision.

celsius*9/5 + 32 — the formula. Go follows normal maths order too: multiply and divide first, then add — identical to the Python version.

fmt.Printf("%.1f°C is %.1f°F\n", ...) — %.1f means “a decimal number rounded to 1 place”. Go does not auto-print floats the way Python’s f-strings do, so you choose the format explicitly — which also means you control it precisely.
Common mistakes — and how to avoid them
✗ Declaring celsius as an int instead of float64 — then 36.6 degrees loses its decimal, and integer division truncates the formula too.
✓ Use float64 for anything that can have a decimal, like temperature.
✗ Writing celsius * 9 / 5 + 32 but expecting celsius * (9 / 5 + 32).
✓ Go does × and ÷ before +, same as ordinary maths. The formula above is already correct as written.
✗ Forgetting strings.TrimSpace before comparing choice to "1" — the trailing newline from ReadString means it never matches.
✓ Always trim a line read with ReadString('\n') before comparing or converting it.

4 Test & Prove Each Part

How do we know the formulas are right? We test them against temperatures we already know — water freezes at 0°C / 32°F and boils at 100°C / 212°F. If those come out right, the formula is right.

Freezing point: 0°C correctly becomes 32°F
Boiling point: 100°C correctly becomes 212°F
The reverse works: 32°F correctly becomes 0°C
Round-trip: convert there and back, get the original number
Goconverter_test.go
package main

import "testing"

func TestFreezingPoint(t *testing.T) {
	if got := cToF(0); got != 32 {
		t.Errorf("cToF(0) = %v; want 32", got)
	}
}

func TestBoilingPoint(t *testing.T) {
	if got := cToF(100); got != 212 {
		t.Errorf("cToF(100) = %v; want 212", got)
	}
}

func TestReverseFreezing(t *testing.T) {
	if got := fToC(32); got != 0 {
		t.Errorf("fToC(32) = %v; want 0", got)
	}
}

func TestRoundTrip(t *testing.T) {
	got := fToC(cToF(25))
	if got < 24.99999 || got > 25.00001 {
		t.Errorf("round trip through both formulas = %v; want ~25", got)
	}
}

Run with go test -v ./.... We pulled the formulas into small functions (cToF, fToC) so the tests can call them directly, without any menu or typed input in the way. Testing against known facts — freezing and boiling points — is a powerful way to trust your maths, in any language.

5 The Interface

The program’s interface — what it asks for and what it gives back — documented plainly.

INPUTchoice + temperature1 or 2, then a number
What it expects
Choose 1 or 2: 1
Enter temperature in Celsius: 100
OUTPUTconverted temperaturethe result with units
What it returns
100.0°C is 212.0°F

6 Run It & Automate It

Save the code as converter.go and run it with go run converter.go — Go compiles and executes in one step, no separate build needed while you are experimenting.

Run it locally
go run converter.go
Pick a direction, type a temperature, and see the conversion.

A CI tool like Jenkins runs go test automatically whenever the code changes — every line below has a plain explanation.

What you should see when it works
Terminala real run
Temperature Converter
1. Celsius to Fahrenheit
2. Fahrenheit to Celsius
Choose 1 or 2: 1
Enter temperature in Celsius: 100
100.0°C is 212.0°F
If it breaks — how to fix it
🚨 strconv.ParseFloat: parsing "": invalid syntax
You pressed Enter without typing a number, or typed something that is not one. Type digits like 25 or 36.6.
🚨 It always prints “Please choose 1 or 2” even when I type 1.
You may have extra spaces or a missing strings.TrimSpace before the switch. The trailing newline from typing Enter must be trimmed first.
GroovyJenkinsfile
// Jenkinsfile — runs the tests automatically every time the code changes.
pipeline {
    agent any                                  // run on any available machine

    stages {
        stage('Get the code') {
            steps { checkout scm }             // download the latest code
        }
        stage('Set up Go') {
            steps {
                sh 'go version'                                 // confirm Go is installed
                sh 'test -f go.mod || go mod init temperature_converter'  // create a module if none exists
            }
        }
        stage('Run the tests') {
            steps {
                sh 'go vet ./...'                    // catch obvious mistakes before running
                sh 'go test -v ./...'                // run every test, show each result
            }
        }
    }

    post {
        success { echo 'All tests passed.' }
        failure { echo 'A test failed — look above.' }
    }
}
🎯 Try this next — make it yours

You have a working converter. Extend it:

  1. Add Kelvin. Offer Celsius→Kelvin too (Kelvin = Celsius + 273.15). (Teaches: more case branches.)
  2. Round differently. Try %.0f for a whole-number answer, or %.2f for more precision. (Teaches: format verbs.)
  3. Keep converting. Wrap the whole thing in a for loop so the user can do many conversions without restarting. (Teaches: an outer loop.)
  4. Guard bad input harder. Instead of quitting on a bad number, loop back and ask again. (Teaches: retry logic.)
What you learned
You learned the ask → calculate → show pattern behind every converter and calculator, plus float64 and strconv.ParseFloat for decimals, switch for choices, and how to test maths against known facts with go test. Related reference: Variables & Types, Control Flow.