在 Python 3.6 中四舍五入到特定数字 [英] Rounding to specific numbers in Python 3.6

查看:44
本文介绍了在 Python 3.6 中四舍五入到特定数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个潜水表,其中的一些数字不在我可以看到的模式中,因此我必须手动添加所有值,但我需要获取输入并将其四舍五入到最接近的字典里的数字.

I'm trying to make a dive table that has some numbers that aren't in a pattern that I can see so I have to manually add all the values, but I need to grab the input and round it to the nearest number in the dictionary.

我需要将输入转换回字符串以使输出正确:

I'll need to convert the input back to string for the output to be correct:

代码:

class DepthTable:

    def __init__(self):
        self.d35 = {"10": "A",
                    "19": "B",
                    "25": "C",
                    "29": "D",
                    "32": "E",
                    "36": "F",
                   }



    def getpressureGroup(self, depth, time):

        if depth == "35":
            output = self.d35[time]
        else:
            output = "No info for that depth"
        print(output)


if __name__ == "__main__":
    depthtable = DepthTable()
    print("Please enter Depth (Use numbers!)")
    depth = input()
    print("Please Enter time!")
    time = input()
    depthtable.getpressureGroup(depth,time)

因此,当玩家"输入时间数字 15 时,我需要将其四舍五入到 19(即使是 13 或类似的数字也始终向上.)我不知道如何使用 round() 或者我可能需要创建一个函数来检查每个数字..

So when the "player" inputs the number 15 for time, I need to round it UP to 19 (Always up even if it's 13 or something like that.) I don't see how I can do this with round() or I might have to make a function that checks EVERY number..

推荐答案

使用您的检查每个数字的函数"的想法,实例变量 keys 可用于获取密钥,如果它存在,或下一个最高键:

Using your idea of a "function that checks EVERY number", an instance variable keys can be used to get the key if it exists, or the next highest key:

class DepthTable:

    def __init__(self):
        self.d35 = {10: "A",
                    19: "B",
                    25: "C",
                    29: "D",
                    32: "E",
                    36: "F",
                   }

        self.keys = self.d35.keys()


    def getpressureGroup(self, depth, time):
        if depth == 35:
            rtime = min([x for x in self.keys if x >= time]) # if exists get key, else get next largest
            output = self.d35[rtime]
        else:
            output = "No info for that depth"
        print(output)


if __name__ == "__main__":
    depthtable = DepthTable()
    print("Please enter Depth (Use numbers!)")
    depth = int(input())
    print("Please Enter time!")
    time = int(input())
    depthtable.getpressureGroup(depth,time)

演示:

Please enter Depth (Use numbers!)
35
Please Enter time!
13
B

<小时>

Please enter Depth (Use numbers!)
35
Please Enter time!
19
B

<小时>

Please enter Depth (Use numbers!)
35
Please Enter time!
10
A

这篇关于在 Python 3.6 中四舍五入到特定数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆