ocaml - 使用尾递归 OCaml 的俄罗斯农民求幂
问题描述
我尝试了俄罗斯农民取幂的无尾递归版本,它返回如下:
let rec fast_expNTR (base, power) =
match power with
|0->1
|n-> if n mod 2=0 then fast_expNTR (square base, power/2)
else base * fast_expNTR(square base , power/2)
但是在 中else base*fast_expNTR(square base , power/2)
,它说表达式应该是 float 类型,但被赋予了 int 类型。我不明白这个错误。
另外,这是我对尾递归快速求幂的尝试:
let fast_exp (base , power)=
let rec helper (acc ,acc2,p)=
if p=0 then acc * acc2
else if p mod 2 =0 then helper(int_of_float (square (float_of_int acc)),acc2, p/2)
else helper(int_of_float(square (float_of_int acc)),acc * acc2, p/2)
in helper(base,1,power)
但它没有计算出正确的结果。请帮忙
解决方案
提示:你的函数square
有类型float -> float
并且*
是整数乘法。
推荐阅读
- amazon-web-services - 将 pyspark 数据帧保存到多个 AWS S3 存储桶
- php - 如何使 openssl_decrypt 在 php 5 中工作
- php - 在碳中获得不正确的子月值
- angular - Angular 通用 SSR:对于已构建的项目,如何在服务器中进行 Angular 调用 localhost,在客户端时如何进行 IP?
- javascript - 在 Javascript 脚本 MVC 中访问 SelectListItem 值和文本
- reactjs - 如何在 VS 代码中为 React 启用 Intellisense?
- python - 过滤多数组字符串
- r - R在函数中使用未定义变量时没有错误消息
- c# - c#中java数组的等价物只有一个索引
- python - lamda 函数无法运行时间比较