当使用整数和浮点数时,Ruby如何解释指数?

时间:2021-02-02 15:58:23

Here's an illustration of what I'm asking about:

这是我要问的问题的一个例子:

当使用整数和浮点数时,Ruby如何解释指数?

I'm just curious about how Ruby is interpreting these problems, which are clearly different as far as Ruby is concerned. I became curious when I was trying to write a simple math problem without using floats and noted that Ruby would read Floats differently than their Integer counterpart (perhaps 1/2 isn't 0.5's counterpart as far as Ruby is concerned, but that's part of what I'm asking here: why not?).

我只是好奇Ruby是如何解释这些问题的,对于Ruby来说,这些问题显然是不同的。当我试图不使用浮点数而编写一个简单的数学问题时,我变得很好奇,并注意到Ruby对浮点数的解读与它们的整数对应数不同(就Ruby而言,也许1/2不是0.5的对应数,但这是我在这里要问的部分:为什么不呢?)

Can anyone explain what's going on here?

谁能解释一下这是怎么回事吗?

2 个解决方案

#1


5  

  • 17424 ** 1 / 2 is interpreted as (17424 ** 1) / 2, which is just 17424/2

    17424 ** 1 /2被解释为(17424 ** 1)/2,也就是17424/2

  • 17424 ** (1 / 2) is counter-intuitive because 1 / 2 is actually 0, not 0.5. This is because when you divide integers, the result's decimal is truncated. You can change one of the operands (or both) to a float to fix this: 17424 ** (1.0 / 2)

    17424 **(1 / 2)是反直觉的,因为1 / 2实际上是0,而不是0。5。这是因为分割整数时,结果的小数被截断。您可以将其中一个操作数(或两个操作数)更改为浮点数,以修复这个问题:17424 ** (1.0 / 2)

#2


2  

17424 ** 1 / 2
    17424  / 2
         8712


17424 ** (1/2)
17424 **   0
      1

/ of two integers is an integer. See also: Why is division in Ruby returning an integer instead of decimal value?

两个整数的/是整数。请参见:为什么Ruby中的除法返回一个整数而不是十进制值?

#1


5  

  • 17424 ** 1 / 2 is interpreted as (17424 ** 1) / 2, which is just 17424/2

    17424 ** 1 /2被解释为(17424 ** 1)/2,也就是17424/2

  • 17424 ** (1 / 2) is counter-intuitive because 1 / 2 is actually 0, not 0.5. This is because when you divide integers, the result's decimal is truncated. You can change one of the operands (or both) to a float to fix this: 17424 ** (1.0 / 2)

    17424 **(1 / 2)是反直觉的,因为1 / 2实际上是0,而不是0。5。这是因为分割整数时,结果的小数被截断。您可以将其中一个操作数(或两个操作数)更改为浮点数,以修复这个问题:17424 ** (1.0 / 2)

#2


2  

17424 ** 1 / 2
    17424  / 2
         8712


17424 ** (1/2)
17424 **   0
      1

/ of two integers is an integer. See also: Why is division in Ruby returning an integer instead of decimal value?

两个整数的/是整数。请参见:为什么Ruby中的除法返回一个整数而不是十进制值?