Last active
January 18, 2021 15:50
-
-
Save angristan/bd23d6aac82ba996c589b860861d71c7 to your computer and use it in GitHub Desktop.
Dirty calculator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"log" | |
"os" | |
"strconv" | |
) | |
func main() { | |
filePath := os.Args[1] | |
operator := os.Args[2] | |
var numbers []int | |
file, err := os.Open(filePath) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer file.Close() | |
scanner := bufio.NewScanner(file) | |
for scanner.Scan() { | |
number, err := strconv.Atoi(scanner.Text()) | |
if err != nil { | |
log.Fatal(err) | |
} | |
numbers = append(numbers, number) | |
} | |
if err := scanner.Err(); err != nil { | |
log.Fatal(err) | |
} | |
total := 0 | |
for k, v := range numbers { | |
if k == 0 { | |
total = v | |
fmt.Println(v) | |
} else { | |
switch operator { | |
case "+": | |
total += v | |
case "*": | |
total *= v | |
} | |
fmt.Printf("%s%d (=%d)\n", operator, v, total) | |
} | |
} | |
operatorStr := "" | |
switch operator { | |
case "+": | |
operatorStr = "addition" | |
case "*": | |
operatorStr = "multiplication" | |
} | |
fmt.Println("-------") | |
fmt.Printf("total = %d (%s)\n", total, operatorStr) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment