开发者

integer division

By definition the integer division returns the quotient.

Why 4613.9开发者_StackOverflow145 div 100. gives an error ("bad argument") ?


For div the arguments need to be integers. / accepts arbitrary numbers as arguments, especially floats. So for your example, the following would work:

1> 4613.9145 / 100.  
46.139145

To contrast the difference, try:

2> 10 / 10.
1.0

3> 10 div 10.
1

Documentation: http://www.erlang.org/doc/reference_manual/expressions.html


Update: Integer division, sometimes denoted \, can be defined as:

a \ b = floor(a / b)

So you'll need a floor function, which isn't in the standard lib.

% intdiv.erl
-module(intdiv).
-export([floor/1, idiv/2]).

floor(X) when X < 0 ->
    T = trunc(X),
    case X - T == 0 of
        true -> T;
        false -> T - 1
    end;

floor(X) -> 
    trunc(X) .

idiv(A, B) ->
    floor(A / B) .

Usage:

$ erl
...
Eshell V5.7.5  (abort with ^G)
> c(intdiv).
{ok,intdiv}
> intdiv:idiv(4613.9145, 100).
46


Integer division in Erlang, div, is defined to take two integers as input and return an integer. The link you give in an earlier comment, http://mathworld.wolfram.com/IntegerDivision.html, only uses integers in its examples so is not really useful in this discussion. Using trunc and round will allow you use any arguments you wish.


I don't know quite what you mean by "definition." Language designers are free to define operators however they wish. In Erlang, they have defined div to accept only integer arguments.

If it is the design decisions of Erlang's creators that you are interested in knowing, you could email them. Also, if you are curious enough to sift through the (remarkably short) grammar, you can find it here. Best luck!


Not sure what you're looking for, @Bertaud. Regardless of how it's defined elsewhere, Erlang's div only works on integers. You can convert the arguments to integers before calling div:

trunc(4613.9145) div 100.

or you can use / instead of div and convert the quotient to an integer afterward:

trunc(4613.9145 / 100).

And trunc may or may not be what you want- you may want round, or floor or ceiling (which are not defined in Erlang's standard library, but aren't hard to define yourself, as miku did with floor above). That's part of the reason Erlang doesn't assume something and do the conversion for you. But in any case, if you want an integer quotient from two non-integers in Erlang, you have to have some sort of explicit conversion step somewhere.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜