我有一个正在尝试的简单的温度转换器类。
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"
我收到以下编译错误
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'
我想念什么?它会将代码的哪一部分推断为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
在你原来的代码5/9
是类型int
和f-32.0
类型为float
。像这样的数值运算符*
要求两个参数都具有相同的类型,因此会出现错误。在固定版本中,我使用5.0/9.0
,它是类型的float
(因为它使用浮点数字文字),因此编译器很高兴。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句