【问题标题】:Floating point conversion and arithmetic浮点数转换和算术
【发布时间】:2017-11-21 15:02:51
【问题描述】:

我刚开始学习 OCaml,我不明白为什么这个函数不能编译。

add_half 将 0.5 添加到列表中的每个值;首先,它们必须以浮点数形式进行投射

示例:

  • 输入:[3;7;19;-4]
  • 输出:[3.5;7.5;19.5;-3.5]

代码:

let rec add_half l = match l with
| [ ] -> [ ]
| x::xs -> let l = float_of_int x
           in (x + 0.5) :: add_half xs

编译器给出以下错误:

Error: This expression has type float but an expression was expected of type int

我怎样才能改变这个功能?

【问题讨论】:

    标签: compiler-errors floating-point type-conversion ocaml


    【解决方案1】:

    首先,当您将 x 转换为浮点数时,您将继续使用 int 值 (x) 而不是转换后的值(令人困惑的名称为 l)。其次,OCaml 具有特定于浮点数的算术运算符,由结尾的 . 表示。因此浮点加法需要+. 运算符。

    这样编译:

    let rec add_half l = match l with
    | [ ] -> [ ]
    | x::xs -> let x' = float_of_int x
               in (x' +. 0.5) :: add_half xs
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-28
      • 1970-01-01
      相关资源
      最近更新 更多