错误 FS0001:类型“int”与类型“float”不匹配

fah*_*ash 4 f#

我正在尝试开发一个简单的温度转换器类。

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 ?

Tom*_*cek 5

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(因为它使用浮点数字文字),因此编译器很高兴。

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