Menu
Coddy logo textTech

まとめ:簡易計算機

CoddyのGOジャーニー「オブジェクト指向プログラミング」セクションの一部。レッスン 11/107。

challenge icon

チャレンジ

難しい

これまで学んだことをすべて使って、完全な Calculator を作成しましょう:

  • 構造体(Exported フィールド)CalculatorName(string)、LastResult(float64)、History(int)とともに定義します
  • コンストラクタ関数NewCalculator(name string)*Calculator を返します。name が empty の場合は、"Unnamed" を default とします
  • 値レシーバGetInfo() は、電卓の名前をフォーマットされた文字列として返します
  • ポインタレシーバAddSubtractMultiply はそれぞれ結果を LastResult に格納し、History をインクリメントします
  • Divide(float64, string) を返すポインタレシーバです。0 で割る場合は、0"Error: division by zero" を返し、HistoryLastResult は更新しません

自分で試してみよう

package main

import "fmt"

func main() {
    var name string
    var a, b float64
    fmt.Scan(&name, &a, &b)

    calc := NewCalculator(name)

    fmt.Println(calc.GetInfo())
    fmt.Printf("History: %d\n", calc.History)

    fmt.Printf("%.0f + %.0f = %.2f\n", a, b, calc.Add(a, b))
    fmt.Printf("%.0f - %.0f = %.2f\n", a, b, calc.Subtract(a, b))
    fmt.Printf("%.0f * %.0f = %.2f\n", a, b, calc.Multiply(a, b))

    result, err := calc.Divide(a, b)
    if err != "" {
        fmt.Println(err)
    } else {
        fmt.Printf("%.0f / %.0f = %.2f\n", a, b, result)
    }

    fmt.Printf("History: %d\n", calc.History)
    fmt.Printf("Last Result: %.2f\n", calc.LastResult)
}

オブジェクト指向プログラミングのすべてのレッスン

自分で練習してみよう: Goオンラインコンパイラ