首页 > 解决方案 > 在幂函数中使用负浮点数时出现错误

问题描述

对于我的float_pow函数,当我使用负 x 进行测试时,例如使用代码float_pow (-2.5) 2,我收到以下错误消息:

“错误:此表达式的类型为 float,但表达式应为 int 类型”。

但如果我这样做float_pow (-.2.5) 2了,那么代码实际上可以工作。如何更改我的代码,以便我不需要在破折号后加上句点?

let rec float_pow x n =
    if n < 0 then
        0.
    else if n = 0 then
        1.
    else
        x *. float_pow x (n - 1);;

标签: floating-pointocamlpow

解决方案


推荐阅读