LoginSignup
0
0

More than 3 years have passed since last update.

【プログラミング初心者】Swift練習問題~九九表示~回答例

Posted at

九九表示

回答例

func printMultiplicationTable() {
    let tableWidth = 9 * 3 + 5 + 1

    // +-------------------------------+
    var topSeparator = ""
    for index in 0..<tableWidth {
        if index == 0 || index == tableWidth - 1 {
            topSeparator += "+"
        } else {
            topSeparator += "-"
        }
    }
    print(topSeparator)

    // 九九の列の数字
    var columnNumber = "|   "
    for column in 1...9 {
        columnNumber += "  \(column)"
    }
    columnNumber += " |"
    print(columnNumber)

    // |  +----------------------------|
    var innerTopSeparator = ""
    for index in 0..<tableWidth {
        if index == 0 {
            innerTopSeparator += "|"
        } else if index > 0 && index < 3 {
            innerTopSeparator += " "
        } else if index == 3 {
            innerTopSeparator += "+"
        } else if index == tableWidth - 1 {
            innerTopSeparator += "|"
        } else {
            innerTopSeparator += "-"
        }
    }
    print(innerTopSeparator)

    // 計算結果表示
    for row in 1...9 {
        var multiplication = "| \(row)| "

        for colmun in 1...9 {
            let number = row * colmun
            var numberStr = String(number)

            if number < 10 {
                numberStr = "0" + numberStr
            }

            multiplication += numberStr + " "
        }

        multiplication += "|"
        print(multiplication)
    }

    // +-------------------------------+
    var bottomSeparator = ""
    for index in 0..<tableWidth {
        if index == 0 || index == tableWidth - 1 {
            bottomSeparator += "+"
        } else {
            bottomSeparator += "-"
        }
    }
    print(bottomSeparator)
}

解説

基本的には力技で表示しています。

print()関数は表示するとき改行されるため、1行を表すStringの変数をそれぞれの行で作り表示します。

let tableWidth = 9 * 3 + 5 + 1で表の横幅を定義します。
九九のデータが「半角スペース+2桁の数字」なので9×3。
右側の「| 1|」が5文字、最後の「|」が一文字なので横幅は「9×3+5+1」となります。

あとは適宜for文を回してそれぞれの行を完成させます。
たまに「+」などが表示されるので、該当するタイミングでif文を使って場合分けします。

計算結果で、結果が一桁の場合「01」などと表示する必要があるので計算結果を確認し、一桁の場合は頭に「0」の文字列を追加しています。

このように複雑な表示をする場合にはforifを使って地道に実装することもあります。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0