2014-06-25 64 views
2

我有一个简单的温度转换器类,我正在努力。错误FS0001:类型'int'与'float'类型不匹配

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的代码是什么部分?

回答

4

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/9int型和f-32.0float类型。数字运算符如*要求两个参数的类型相同,因此会出现错误。在固定版本中,我使用5.0/9.0,它的类型为float(因为它使用浮点数字文字),因此编译器很高兴。

+0

即使两个整数的划分不是推断为单个或浮点? – fahadash

+2

不,它是一个整数除法“9/5 = 1”,而“9.0/5.0 = 1.8”。事实上,使用整数除法,然后将结果转换为浮点数将是一个错误,因为您会得到1而不是1.8! –