Go: Format a score table

Printf can line text up in columns, which makes output easy to read.

What to build

A program that prints three test results as an aligned table.

Requirements

  • Read three lines, each with a name, a score and a total.
  • Print the header Name Score Percent first: the name column is 10 wide and left-aligned, the score column 6 wide and the percent column 9 wide, both right-aligned.
  • For each line print the name left-aligned in 10 characters, the score right-aligned in 6, and the percent (score * 100 / total) with one decimal, right-aligned in 9, followed by %.

Input

Three lines, each with a name (one word), a score and a total (whole numbers).

Output

A header line and three rows.

Constraints

Names have at most 10 letters; 0 ≤ score ≤ total ≤ 1000 and total > 0.

Example

Input:

Ada 45 50
Linus 30 50
Grace 50 50

Output:

Name       Score  Percent
Ada           45    90.0%
Linus         30    60.0%
Grace         50   100.0%

Why it works

%-10s pads text on the right and %6d pads numbers on the left, so the columns line up. Multiplying by 100.0 makes the division use decimals instead of whole numbers.

Examples

Example 1 · Input
Ada 45 50
Linus 30 50
Grace 50 50
Expected output
Name       Score  Percent
Ada           45    90.0%
Linus         30    60.0%
Grace         50   100.0%
Example 2 · Input
Tim 7 8
Ken 1 3
Dennis 0 10
Expected output
Name       Score  Percent
Tim            7    87.5%
Ken            1    33.3%
Dennis         0     0.0%

Hints

Hint 1

Use %-10s for left-aligned text and %6d for a right-aligned number in a field of width 6.

Hint 2

Use %9.1f for the percent and %% to print a percent sign.

Solution

Show one correct solution (try it yourself first)
package main

import "fmt"

func main() {
	fmt.Printf("%-10s%6s%9s\n", "Name", "Score", "Percent")
	for i := 0; i < 3; i++ {
		var name string
		var score, total int
		fmt.Scan(&name, &score, &total)
		percent := float64(score) * 100.0 / float64(total)
		fmt.Printf("%-10s%6d%8.1f%%\n", name, score, percent)
	}
}

▶ Open this solution in the compiler

Lesson: Your first Go program →