[英]Python Floating and Integer Numbers
I want check a type of a number in python, for example 我想检查python中数字的类型,例如
x=4
y=2
type(x/y) == type(int)
--> False
it has to be True but what python makes is, it takes 4/2
as 2.0
. 它必须为True,但是python所做的是,它需要
4/2
作为2.0
。
2.0
is a floating number, how can I make 2.0
to 2
but at the same time I don't want to make 2.5
to 2
for example : 2.0
是一个浮点数,我怎样才能使2.0
等于2
但同时我不想让2.5
等于2
:
x=5
y=2
type(x/y) == type(int)
--> False
This is what I want. 这就是我要的。 In conclusion I need something that can understand if a number is int or a floating number after a division operation.
总之,我需要一些可以理解除法运算后数字是整数还是浮点数的东西。 Can you help me please
你能帮我吗
The output of /
is going to be a float. /
的输出将是一个浮点数。 You can define your own function that wraps /
您可以定义自己的包装
/
的函数
import math
def my_div(a, b):
x = a/b
if math.floor(x) == x:
return int(x)
return x
In python 3, x/y
will always be of type float
, so forget about type
在python 3中,
x/y
始终为float
类型,因此请忽略type
If you only have int numbers as input you could just use modulo: 如果仅将整数作为输入,则可以使用模数:
x%y == 0
yields True
if the result is integer, False
otherwise 如果结果是整数,则产生
True
,否则产生False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.