我正在尝试开发一个简单的温度转换器类。
open System
type Converter() =
member this.FtoC (f : float) = (5/9) * (f - 32.0)
member this.CtoF(c : float) = (9/5) * c + 32.0
let conv = Converter()
54.0 |> conv.FtoC |> printfn "54 F to C: %A"
32.0 |> conv.CtoF |> printfn "32 C to F: %A"
Run Code Online (Sandbox Code Playgroud)
我收到以下编译错误
prog.fs(4,46): error FS0001: The type 'float' does not match the type 'int'
prog.fs(4,39): error FS0043: The type 'float' does not match the type 'int'
Run Code Online (Sandbox Code Playgroud)
我缺少什么?它将代码的哪一部分推断为 int ?
F# 不会自动将整数转换为浮点数,因此您需要:
type Converter() =
member this.FtoC (f : float) = (5.0/9.0) * (f - 32.0)
member this.CtoF(c : float) = (9.0/5.0) * c + 32.0
Run Code Online (Sandbox Code Playgroud)
在您的原始代码中,5/9属于类型int并且f-32.0属于类型float。像这样的数字运算符*要求两个参数具有相同的类型,因此您会收到错误。在固定版本中,我使用了5.0/9.0,它是类型float(因为它使用浮点数字文字),因此编译器很高兴。
| 归档时间: |
|
| 查看次数: |
3861 次 |
| 最近记录: |