标签归档:absolute-value

如何将负数转换为正数?

问题:如何将负数转换为正数?

如何在Python中将负数转换为正数?(并保持积极的态度。)

How can I convert a negative number to positive in Python? (And keep a positive one.)


回答 0

>>> n = -42
>>> -n       # if you know n is negative
42
>>> abs(n)   # for any n
42

不要忘记检查文档

>>> n = -42
>>> -n       # if you know n is negative
42
>>> abs(n)   # for any n
42

Don’t forget to check the docs.


回答 1

简单地乘以-1就可以双向工作…

>>> -10 * -1
10
>>> 10 * -1
-10

simply multiplying by -1 works in both ways …

>>> -10 * -1
10
>>> 10 * -1
-10

回答 2

如果“保留一个正数”表示您希望一个正数保持正数,而且还希望将一个负数转换为正数,请使用abs()

>>> abs(-1)
1
>>> abs(1)
1

If “keep a positive one” means you want a positive number to stay positive, but also convert a negative number to positive, use abs():

>>> abs(-1)
1
>>> abs(1)
1

回答 3

内置函数abs()可以解决问题。

positivenum = abs(negativenum)

The inbuilt function abs() would do the trick.

positivenum = abs(negativenum)

回答 4

In [6]: x = -2
In [7]: x
Out[7]: -2

In [8]: abs(x)
Out[8]: 2

实际上abs将返回absolute value任何数字。绝对值始终是非负数。

In [6]: x = -2
In [7]: x
Out[7]: -2

In [8]: abs(x)
Out[8]: 2

Actually abs will return the absolute value of any number. Absolute value is always a non-negative number.


回答 5

如果您使用numpy,则可以使用

import numpy as np
np.abs(-1.23)
>> 1.23

它将提供绝对值。

If you are working with numpy you can use

import numpy as np
np.abs(-1.23)
>> 1.23

It will provide absolute values.