阶乘函数输入int,输出real?
这绝对让我发疯。我能想象到的最简单的事情我却做不到。
我只想计算阶乘输入一个整数并输出一个实数。
我尝试过以多种方式强制。
fun factorial 0 = 1 |
factorial n = n * factorial(n-1);
This is absolutely driving me nuts. The supposed simplest thing I can imagine and I can't do it.
I just want to computer factorial inputting an int and output a real.
I've tried to coerce in numerous way.
fun factorial 0 = 1 |
factorial n = n * factorial(n-1);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要将 int 转换为实数,请使用
Real.fromInt
。如果要返回实数,还应该返回1.0
而不是1
作为基本情况。所以你的代码变成:To convert an int to a real, you use
Real.fromInt
. If you want to return reals, you should also return1.0
instead of1
as the base case. So your code becomes:从数学上来说,n! = (n-1)! * n .除非我误解了事情(这是可能的;我不懂机器学习),否则你的函数将始终返回 1,因为它永远不会乘以 n。
我不知道你如何返回一个实数而不是一个整数,也不知道这段代码是否做到了这一点,但至少它应该给你一个正确的值。
Mathematically, n! = (n-1)! * n . Unless i'm misunderstanding things (which is possible; i don't know ML), your function will always return 1 because it's never multiplying by n.
I don't know how you return a real rather than an int, or whether this code even does it, but at the very least it should give you a correct value.
http://www.standardml.org/Basis/real.html #SIG:REAL.fromInt:VAL
http://www.standardml.org/Basis/real.html#SIG:REAL.fromInt:VAL