discord_programmieraufgaben/2025-10-11_1/rechner.go (view raw)
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 62 63 |
package main
import (
"fmt"
"bufio"
"os"
"log"
"strconv"
)
func readInput() *string {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Rechnung: ")
text, err := reader.ReadString('\n')
if err != nil {
log.Fatal(err)
}
text = text[:len(text)-1]
return &text
}
func parseCalculation(calculation *string) *int64 {
for i := 0; i < len(*calculation); i++ { // no range because unicode would be wasteful
if (*calculation)[i] == '+' {
left, err := strconv.ParseInt((*calculation)[:i], 10, 64)
if err != nil {
log.Fatal(err)
}
right, err := strconv.ParseInt((*calculation)[i+1:], 10, 64)
if err != nil {
log.Fatal(err)
}
switch (*calculation)[i] {
case '+':
add(&left, &right)
default:
log.Fatal("Unbekanntes Rechenzeichen")
}
}
}
singleNumber, err := strconv.ParseInt(*calculation, 10, 64)
if err != nil {
log.Fatal("Invalide Zahl")
}
return &singleNumber
}
func add(left *int64, right *int64) {
*left = *left + *right
}
func main() {
inputptr := readInput()
resultptr := parseCalculation(inputptr)
fmt.Printf("Ergebnis: %d", *resultptr)
}
|