我坐在这上面超过4个小时,不能把头包裹起来。 我尝试运行以下代码:
top = 100 :: Int
couplesToOne num
|num<0 = error "num<0"
|num==0 = 0
|num `mod` 2 == 0 = num `div` 2
|num `mod` 2 == 1 = (num+1) `div` 2
|otherwise = error "otherwise"
numInBig n bigSide
|(bigSide^2 <= n) = couplesToOne (n-1)
|(bigSide^2 > n) = couplesToOne (n-1) - (couplesToOne (floor(sqrt(bigSide^2 - n))))
|otherwise = error "otherwise"
ans = map (numInBig top) [3..((div top 4) + 1)]
我收到以下错误消息:
No instance for (RealFrac Int) arising from a use of `numInBig'
In the first argument of `map', namely `(numInBig top)'
In the expression: map (numInBig top) [3 .. ((div top 4) + 1)]
In an equation for `ans':
ans = map (numInBig top) [3 .. ((div top 4) + 1)]
enter code here
我想(可能是?)这是因为“sqrt”返回一个浮点数,但这就是为什么我添加了应该返回积分的地板。
你能帮我吗?答案 0 :(得分:3)
这有效:
top = 100 :: Int
couplesToOne num
|num<0 = error "num<0"
|num==0 = 0
|num `mod` 2 == 0 = num `div` 2
|num `mod` 2 == 1 = (num+1) `div` 2
|otherwise = error "otherwise"
numInBig n bigSide
|(bigSide^2 <= n) = couplesToOne (n-1)
|(bigSide^2 > n) = couplesToOne (n-1) - couplesToOne (floor(sqrt(fromIntegral(bigSide^2 - n))))
|otherwise = error "otherwise"
ans = map (numInBig top) [3..((div top 4) + 1)]
您需要额外fromIntegral
,因为sqrt::Floating a => a -> a
未定义Int
。
> ans
[50,50,50,50,50,50,50,50,48,47,46,45,44,44,43,43,42,41,41]