velpandian
velpandian

Reputation: 471

How does the expr command work?

puts "-1/2 is [expr -1/2]"

For the above, the output is:

-1/2 is -1

I don't know how it's working.

Upvotes: 0

Views: 422

Answers (1)

Jerry
Jerry

Reputation: 71558

When you use -1/2, you are passing the division of two integers to the interpreter and hence are telling it to do an integer division, which returns the closest integer, smaller than the result otherwise.

For instance, -1/2 gives -0.5, and -1 is the closest integer below -0.5.

Some other examples:

% expr 5/2    ;# Should give 2.5, closest integer down is 2
2
% expr -5/2   ;# Should give -2.5, closest integer down is -3
-3
% expr 5/-2   ;# Should give -2.5, closest integer down is -3
-3

If you want to get -0.5 as result, you can either change one of the two values to be a float number...

% expr -1.0/2
-0.5
% expr -1/2.0
-0.5

Or use double on either number

% expr double(-1)/2
-0.5
% expr -1/double(2)
-0.5

Note that for better speed and prevention of injection, you might want to brace your expressions

Upvotes: 5

Related Questions