Ruby arithmetic operations =S

F

Flaab Mrlinux

Hi there

I have to do a program for the first time that needs some math...and
which is my surprise that num mod num to get the modulus of a division
does not work! neither num div num to the the integer result of it.

All the rest of math operands work fine xDDD But how do i do:

a) A float division ( 5 / 2 = 2.5)
b) A mod division ( 5 mod 2 = 1)
c) An integer division =S (5 div 2 = 2)

Thx! xD
 
R

Rimantas Liubertas

All the rest of math operands work fine xDDD But how do i do:
a) A float division ( 5 / 2 = 2.5)
b) A mod division ( 5 mod 2 = 1)
c) An integer division =S (5 div 2 = 2)

In ruby when you divide integers, you get integer division. If you
want float, use floats (just add
point zero).


Regards,
Rimantas
 
O

oinkoink

5 / 2.0
In ruby when you divide integers, you get integer division. If you
want float, use floats (just add
point zero).

It's not quite so simple.=> 5/2
....where the last "5/2" is a rational number. If you want to do
integer division "portably" (i.e., in a way that is compatible with the
mathn standard library having been required earlier in the program),
you should use "div"=> [2,1]
If you wish to use the Rational, Complex, or Matrix classes in the
standard library, you will need to require mathn to avoid strange and
even downright buggy behavior. But this redefines the meaning of
expressions like 5/2.
 
B

Bernard Kenik

----- Original Message -----
From: "Flaab Mrlinux" <[email protected]>
Newsgroups: comp.lang.ruby
To: "ruby-talk ML" <[email protected]>
Sent: Thursday, November 16, 2006 5:46 PM
Subject: Ruby arithmetic operations =S

Hi there

I have to do a program for the first time that needs some math...and
which is my surprise that num mod num to get the modulus of a division
does not work! neither num div num to the the integer result of it.

All the rest of math operands work fine xDDD But how do i do:

a) A float division ( 5 / 2 = 2.5)
b) A mod division ( 5 mod 2 = 1)
c) An integer division =S (5 div 2 = 2)

Thx! xD
float division x = 5.0 / 2 or x = 5 /2.0 or x 5.0/2.0
mod division x = 5 % 2
integer division x = 5 / 2
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top