Course outline
Course / The terminal and the language

Convert before you divide

Lab

How to fetch and submit this lab

Once: install the tool and connect your account.

curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon login

Each lab: download it, edit the file named in the instructions, then submit.

gonomicon fetch week-1/08-07-average-needs-float
cd 08-07-average-needs-float
gonomicon submit

Go installed? gonomicon test runs the visible test on your computer first. Submitting also runs hidden checks on our server.

Goal

Finish Average so it divides Total by Count and keeps the decimals. Total and Count are whole numbers, so you have to convert them before you divide.

Example

If a function had to average a score over a number of rounds, you would write:

var Score = 9
var Rounds = 4

func Mean() float64 {
	return float64(Score) / float64(Rounds)
}

9 / 4 with whole numbers gives 2. After converting both to float64, it gives 2.25.

Rules

  • Edit average.go. Average has a // TODO comment and a return line you will change.
  • Average must return Total divided by Count as a float64, with the decimals kept. For example, 7 and 2 give 3.5.
  • Convert with float64( ... ). Do not type the numbers into the function: the tests change Total and Count, and Average has to follow them.
  • Do not change the var Total and var Count lines, or the first line of Average.
  • Do not add imports. You will not need any.

What you'll practice

Converting an int to a float64 with float64(value), and why dividing two whole numbers loses the decimals.

Run it

gonomicon fetch week-1/08-07-average-needs-float
cd 08-07-average-needs-float
gonomicon test
gonomicon submit

Hints

  1. Total and Count are whole numbers, and dividing two whole numbers throws away the decimals. Convert them to float64 first.
  2. The shape is float64(Total) / float64(Count). The conversion goes around each name, not around the finished division.
  3. Replace the return line with: return float64(Total) / float64(Count). Do not change Total or Count themselves.

Something wrong with this lesson? Report a problem