Haskell将Int转换为Float [英] Haskell Converting Int to Float

查看:250
本文介绍了Haskell将Int转换为Float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



基本上我需要接受两个Int参数。

我有一个新函数的问题,它是fromIntegral函数。并返回数字的百分比,但当我运行我的代码,它不断给我这个错误:

代码:

  percent :: Int  - > Int  - >浮动
%xy = 100 *(a`div` b)
其中a = fromIntegral x :: Float
b = fromIntegral y :: Float

错误:

 没有用于(Integral Float )
使用'div'
可能的修正:为(Integral Float)
添加一个实例声明在'(*)'的第二个参数中,即`(a`div `b)'
在表达式中:100 *(a`div` b)
在'百分比'的等式中:
%xy
= 100 *(a`div `b)
其中
a = fromIntegral x :: Float
b = fromIntegral y :: Float

我读过'98 Haskell前奏,它说有这样一个叫fromInt的函数,但它从来没有工作,所以我不得不这样做,但它仍然无法正常工作。帮助!

解决方案

查看 div 的类型:

  div :: Integral a => a  - > a  - > a 

您无法将您的输入转换为 Float 然后使用 div



使用(/)改为:

 (/)::小数a => a  - > a  - > a 

以下代码有效:

  percent :: Int  - > Int  - >浮动
%xy = 100 *(a / b)
其中a = fromIntegral x :: Float
b = fromIntegral y :: Float


I'm having some problem with one of the functions which I'm new at, it's the fromIntegral function.

Basically I need to take in two Int arguments and return the percentage of the numbers but when I run my code, it keeps giving me this error:

Code:

percent :: Int -> Int -> Float
percent x y =   100 * ( a `div` b )
where   a = fromIntegral x :: Float
        b = fromIntegral y :: Float

Error:

No instance for (Integral Float)
arising from a use of `div'
Possible fix: add an instance declaration for (Integral Float)
In the second argument of `(*)', namely `(a `div` b)'
In the expression: 100 * (a `div` b)
In an equation for `percent':
    percent x y
      = 100 * (a `div` b)
      where
          a = fromIntegral x :: Float
          b = fromIntegral y :: Float

I read the '98 Haskell prelude and it says there is such a function called fromInt but it never worked so I had to go with this but it's still not working. Help!

解决方案

Look at the type of div:

div :: Integral a => a -> a -> a

You cannot transform your input to a Float and then use div.

Use (/) instead:

(/) :: Fractional a => a -> a -> a

The following code works:

percent :: Int -> Int -> Float
percent x y =   100 * ( a / b )
  where a = fromIntegral x :: Float
        b = fromIntegral y :: Float

这篇关于Haskell将Int转换为Float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆