将浮点数转换为整数 [英] Converting Floating to Integer

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

问题描述

我试图定义:

I am trying to define:

square :: Integer -> Integer 
square = round . (** 2)

我得到:

and I am getting:

<interactive>:9:9: error:
    • No instance for (RealFrac Integer) arising from a use of ‘round’
    • In the first argument of ‘(.)’, namely ‘round’
      In the expression: round . (** 2)
      In an equation for ‘square’: square = round . (** 2)

<interactive>:9:18: error:
    • No instance for (Floating Integer)
        arising from an operator section
    • In the second argument of ‘(.)’, namely ‘(** 2)’
      In the expression: round . (** 2)
      In an equation for ‘square’: square = round . (** 2)

我在这种语言中仍然是新手,我似乎无法将浮点到整数的实例。有谁知道我该怎么做?

I am still new in this language and I seem to be unable to convert an instance of Floating to an Integer. Does anybody know how can I do so?

推荐答案

Haskell具有多种不同类型的指数函数:

Haskell has multiple exponent functions with different types:

  • (^) :: (Num a, Integral b) => a -> b -> a
  • (^^) :: (Fractional a, Integral b) => a -> b -> a
  • (**) :: Floating a => a -> a -> a

您正在寻找的那只是( ^)。有了它,你甚至不需要 round

The one you are looking for is just (^). With it, you don't even need round:

square :: Integer -> Integer 
square = (^ 2)

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

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