Arithmetic gives unexpected value in ruby
Why is this:
((256-438)^2)+((227-298)^2)
Giving me -253
when i开发者_JAVA技巧t should be 38165
instead?
^
is the bitwise exclusive OR operator (XOR)
**
is the exponent operator, use:
((256-438)**2)+((227-298)**2)
Because ^
is the operator for XOR, not exponents. Try **
instead.
Try ((256-438)**2)+((227-298)**2)
^
is the bitwise XOR operator, according to http://phrogz.net/programmingruby/language.html. Not the "power of" operator.
^
is the XOR operator, not exponeniation.
Use **
not ^
Code should be - ((256-438)**2)+((227-298)**2)
**
is the Exponentiation or 'power of' operator.
The Exponentiation operator
Raises
number
to the power ofsecond number
, which may be negative or fractional.
2 ** 3 #=> 8
2 ** -1 #=> (1/2)
2 ** 0.5 #=> 1.4142135623731
^
is the bitwise XOR operator.
The XOR operator
The XOR operator implements an exclusive OR which means that it will set the bit to 1 in the output if only one of the corresponding bits in the inputs are set to 1:
(a = 18).to_s(2) #=> "10010"
(b = 20).to_s(2) #=> "10100"
(a ^ b).to_s(2) #=> "110"
(leading zeros are omitted)
精彩评论