英文:
Why does calling int() on a negative number return the integer under it?
问题
我发现Microsoft Access数据库的VBA中有一个函数,它使用这个操作来将一个数字向上舍入:
例如,将12.34传递给RoundUp()
函数会返回13,将-12.34传递给它会返回-12,这意味着这个函数实际上是将数字向上舍入,这令人惊讶。
这个函数的工作方式显然是通过取传递的数字的负数的整数部分。
对于12.34,它应该取**-12.34的整数部分,所以是-12**,而不是**-13**?
这真是出乎意料的。
当我在Python中尝试使用这个函数时,不知道会得到什么结果,Python显示给我12。
这意味着,当取**-12.34的整数部分时,这是传递的数字的负数,它得到了-12**。
为什么VBA会这样做?或者我对Python的int()
函数的行为有误解吗?
TL;DR:
在VBA中尝试获取负数的整数部分会返回比它小的数字,就好像它只是将其向下舍入。
为什么?
英文:
I stumbled upon a function in a Microsoft Access Database's VBA that uses this operation to round a number up :
For example, passing 12.34 to the RoundUp()
function returned 13, and passing -12.34 returned -12, Meaning this function actually rounds up numbers, which is surprising.
The way this function works is obviously by taking the integer part of the negative of the passed number.
For 12.34 it should take the integer part of -12.34, so -12, not -13?
This was quite unexpected.
When I tried in python, not knowing what expecting, with this function :
Python showed me 12.
Meaning, when taking the integer part of -12.34, which is the negative of the passed number, it got -12.
Why does VBA do this ? Or am I mistaken on what should python's int()
do ?
TL;DR :
Trying to get the integer part of a negative number in VBA returns the number under it, as if it just rounded it down.
Why ?
答案1
得分: 1
这是如何实现 Int
的方式实现:
Int(number)
,Fix(number)
Int
和Fix
的区别在于,如果 number 是负数,Int
返回小于或等于 number 的第一个负整数,而Fix
返回大于或等于 number 的第一个负整数。
如果您想要后一种选项,请使用 Fix
。
英文:
This is how Int
is implemented:
> Int(number)
,Fix(number)
>
> The difference between Int
and Fix
is that if number is negative, Int
returns the first negative integer less than or equal to number, whereas Fix
returns the first negative integer greater than or equal to number.
Use Fix
if you want the latter option.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论