python 2.7:将一个浮点数循环到下一个偶数 [英] python 2.7: round a float up to next even number
本文介绍了python 2.7:将一个浮点数循环到下一个偶数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
步骤:
$ b $ 1)检查一个数字是奇数还是偶数
2)如果奇数,凑到下一个偶数
我已经准备好了第一步,这个函数检查给定的数字是偶数还是不是:
def is_even(num):
if(float(num)* 10)%2 == 0:
returnTrue
else:
returnFalse
任何建议?
注意:所有的浮动将是正面的。
解决方案
没有必要第1步。只需将值除以2,
导入数学
def round_up_to_even(f):
return math.ceil(f / 2)* 2
演示:
>>>导入数学
>>> def round_up_to_even(f):
... return math.ceil(f / 2)* 2
...
>>> round_up_to_even(1.25)
2
>>> round_up_to_even(3)
4
>>> round_up_to_even(2.25)
4
I would like to round up a float to the next even number.
Steps:
1) check if a number is odd or even
2) if odd, round up to next even number
I have step 1 ready, a function which checks if a give number is even or not:
def is_even(num):
if int(float(num) * 10) % 2 == 0:
return "True"
else:
return "False"
but I'm struggling with step 2....
Any advice?
Note: all floats will be positive.
解决方案
There is no need for step 1. Just divide the value by 2, round up to the nearest integer, then multiply by 2 again:
import math
def round_up_to_even(f):
return math.ceil(f / 2.) * 2
Demo:
>>> import math
>>> def round_up_to_even(f):
... return math.ceil(f / 2.) * 2
...
>>> round_up_to_even(1.25)
2
>>> round_up_to_even(3)
4
>>> round_up_to_even(2.25)
4
这篇关于python 2.7:将一个浮点数循环到下一个偶数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文