简体   繁体   English

如果小数点后没有有效数字,则获取 integer;如果小数点后有有效数字,则获取浮点数 python

[英]Get a integer if there are no significant digits after decimal or get a float if there are significant digits after decimal in python

I was recently doing a question on geeks for geeks website where they required median of two sorted arrays, but they are asking answer to be a int if there are no digits after decimals or a float if there are digits after decimals.我最近在 geeks for geeks 网站上做了一个问题,他们要求两个排序的 arrays 的中位数,但是如果小数点后没有数字,他们要求答案是 int,如果小数点后有数字,则答案是 float。 For example when giving median of even number arrays, we usually divide middle elements with two, so if middle elements are 2 and 4 then after division answer should be 3 , or if elements are 3 and 4 answer should be 3.5 .例如,当给出偶数 arrays 的中位数时,我们通常将中间元素除以二,因此如果中间元素是24那么除法后的答案应该是3 ,或者如果元素是34答案应该是3.5 But if we use / operator in python it will return division of 2 and 4 as 3.0 , and if we use // operator it will return division of 3 and 4 as 3 instead of 3.5 .但是,如果我们在 python 中使用/运算符,它将返回24的除法作为3.0 ,如果我们使用//运算符,它将返回34的除法作为3而不是3.5 Is there any way to get around this instead of checking divisibility by 2.有什么办法可以解决这个问题而不是检查 2 的整除性。

You could try something like this potentially.你可以潜在地尝试这样的事情。 Do the division as normal and then apply the following:正常进行除法,然后应用以下内容:

if int(x) == x: # will be true if x=5.0 but not if x = 5.5
  x = int(x) 
  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM