-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsv-reader.go
More file actions
61 lines (49 loc) · 1.11 KB
/
csv-reader.go
File metadata and controls
61 lines (49 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package main
import (
"encoding/csv"
"fmt"
"io"
"os"
"strconv"
"strings"
)
func main() {
file, err := os.Open("dados.csv")
defer file.Close()
if err != nil {
fmt.Println("Erro ao abrir o arquivo csv: ", err)
return
}
reader := csv.NewReader(file)
vendas := make(map[int][]Venda)
for {
row, err := reader.Read()
if err == io.EOF {
fmt.Println("Arquivo acabou")
break
}
if err != nil {
fmt.Println("Erro ao ler linha: ", err)
return
}
dadosVenda := strings.Split(row[0], ";")
mes, _ := strconv.Atoi(dadosVenda[0])
nome := dadosVenda[1]
valor, _ := strconv.ParseFloat(dadosVenda[2], 32)
venda := Venda{Mes: mes, Vendedor: nome, Valor: valor}
vendas[venda.Mes] = append(vendas[venda.Mes], venda)
}
vendas[0] = nil
for chave, valor := range vendas {
fmt.Printf("A media de vendas do mês %d foi: %.2f", chave, calculaMediaVendas(valor))
fmt.Println("")
}
}
func calculaMediaVendas(v []Venda) float64 {
somaVendas := 0.00
quantidadeVendas := len(v)
for i := 0; i < quantidadeVendas; i++ {
somaVendas += v[i].Valor
}
return somaVendas / float64(quantidadeVendas)
}