2014年8月2日土曜日

開発環境

Practical Programming: An Introduction to Computer Science Using Python 3 (Pragmatic Programmers) (Paul Gries (著)、Jennifer Campbell (著)、Jason Montojo (著)、Lynn Beighley (編集)、Pragmatic Bookshelf)のChapter 5(Making Choices)、5.6(Exercises) 8.をSwiftで考えてみる。

5.6(Exercises) 8.

コード(Xcode)

converter.swift

//
//  converter.swift
//  convert-temperatures
//
//  Created by kamimura on 8/2/14.
//  Copyright (c) 2014 kamimura. All rights reserved.
//

import Foundation

func convertToCelsius(t:Float, source:String) -> Float? {
    switch source {
    case "Kelvin": return t - 273.15
    case "Celsius": return t
    case "Fahrenheit": return (t - 32) * 5 / 9
    case "Rankine": return (t - 491.67) * 5 / 9
    case "Delisle": return 100 - t * 2 / 3
    case "Newton": return t * 100 / 33
    case "Reaumur": return t * 5 / 4
    case "Romer": return (t - 7.5) * 40 / 21
    default: return nil
    }
}

func convertFromCelsius(t:Float, target:String) -> Float? {
    switch target {
    case "Kelvin":return t + 273.15
    case "Celsius": return t
    case "Fahrenheit": return t * 9 / 5 + 32
    case "Rankine": return (t + 273.15) * 9 / 5
    case "Delisle": return (100 - t) * 3 / 2
    case "Newton": return t * 33 / 100
    case "Reaumur": return t * 4 / 5
    case "Romer": return t * 21 / 40 + 7.5
    default: return nil
    }
}

func convertTemperatures(t:Float, source:String, target:String) -> Float {
    return convertFromCelsius(convertToCelsius(t, source)!, target)!
}

main.swift

//
//  main.swift
//  convert-temperatures
//
//  Created by kamimura on 8/2/14.
//  Copyright (c) 2014 kamimura. All rights reserved.
//


let units = ["Kelvin", "Celsius", "Fahrenheit", "Rankine", "Delisle","Newton", "Reaumur", "Romer"]

println("Absolute zero")
for target:String in units {
    let temp = convertTemperatures(0, "Kelvin", target)
    println("\(target): \(temp)")
}

println("Ice melts")
for target in units {
    let temp = convertTemperatures(32, "Fahrenheit", target)
    println("\(target): \(temp)")
}

入出力結果(Console Output, Assistant Editor)

Absolute zero
Kelvin: 0.0
Celsius: -273.149993896484
Fahrenheit: -459.669982910156
Rankine: 0.0
Delisle: 559.724975585938
Newton: -90.1395034790039
Reaumur: -218.519989013672
Romer: -135.903747558594
Ice melts
Kelvin: 273.149993896484
Celsius: 0.0
Fahrenheit: 32.0
Rankine: 491.669982910156
Delisle: 150.0
Newton: 0.0
Reaumur: 0.0
Romer: 7.5
Program ended with exit code: 0

0 コメント:

コメントを投稿