I need a function which gets two Int
s (a
and b
) and returns A/B
as Int
. I am sure that A/B
will always be an integer.
Here is my solution:
myDiv :: Int -> Int -> Int myDiv a b = let x = fromIntegral a y = fromIntegral b in truncate (x / y)
But want to find more simpler solution. Something like this:
myDiv :: Int -> Int -> Int myDiv a b = a / b
How can I divide Int to Int and get Int ?
When dividing two numbers of the same type (integers, doubles, etc.) the result will always be of the same type (so 'int/int' will always result in int). In this case you have double var = integer result which casts the integer result to a double after the calculation in which case the fractional data is already lost.
When dividing an integer by an integer, the answer will be an integer (not rounded).
Use the floor division operator // to return an integer from integer division, e.g. result_1 = 30 // 6 . The floor division operator will always return an integer and is like using mathematical division with the floor() function applied to the result.
Division of two numbers always returns an integer value.
Why not just use quot
?
quot a b
is the integer quotient of integers a and b truncated towards zero.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With