什么是正确的方法来划分两个Int值来获得Float? [英] What's the right way to divide two Int values to obtain a Float?
问题描述
我想在Haskell中分两个 Int
值并获得结果作为 Float
。我尝试这样做:
foo :: Int - > Int - >浮动
foo ab = fromRational $ a%b
但GHC(版本6.12.1)告诉我对于表达式中 a
的推断类型'Int',无法匹配预期的类型'整数'。
我明白为什么: 正确的做法是什么?我应该在我的操作数上调用 您必须将操作数转换为浮动 first 然后除,否则你将执行一个整数除法(无小数位)。 Laconic解决方案(需要 with I'd like to divide two but GHC (version 6.12.1) tells me "Couldn't match expected type 'Integer' against inferred type 'Int'" regarding the I understand why: the What's the right way to do this? Should I just call You have to convert the operands to floats first and then divide, otherwise you'll perform an integer division (no decimal places). Laconic solution (requires which is short for with
这篇关于什么是正确的方法来划分两个Int值来获得Float?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!(%)
产生一个 Ratio Integer
,所以操作数必须是 Integer
而不是 Int
。但是我分割的值远不及 Int
的范围限制,所以使用任意精度的bignum类型似乎是过度杀伤。 $ b 到Integer
,还是有一个更好的方法(也许不涉及(%)
和比率),我不知道?
Data.Function
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ / pre>
foo ab =(fromIntegral a)/(fromIntegral b)
foo :: Int - > Int - >浮动
Int
values in Haskell and obtain the result as a Float
. I tried doing it like this:foo :: Int -> Int -> Float
foo a b = fromRational $ a % b
a
in the expression.fromRational
call requires (%)
to produce a Ratio Integer
, so the operands need to be of type Integer
rather than Int
. But the values I'm dividing are nowhere near the Int
range limit, so using an arbitrary-precision bignum type seems like overkill.toInteger
on my operands, or is there a better approach (maybe one not involving (%)
and ratios) that I don't know about?Data.Function
)foo = (/) `on` fromIntegral
foo a b = (fromIntegral a) / (fromIntegral b)
foo :: Int -> Int -> Float