0

我对 Python2.7 非常陌生(就像第 1 天一样),我正在尝试编写一个简单的密耳到度数转换程序作为学习练习。程序要求用户选择将度数转换为密耳,反之亦然,然后询问一个值。它相应地除以或相乘并打印转换后的答案。这就是问题出现的地方。转换后的答案不应作为精确的浮点数返回。例如 - 如果用户输入 6400 密耳,我希望程序返回 360 度(1 度 = 17.78 密耳),而不是 359.955 度。我对 round 函数的(有限)理解是它接受浮点数和精度级别,但不接受变量。如何将总和传递给round()?

非常感谢您的意见。

import sys
import math

def menu():

    print ""
    print " Mils / Degrees Conversion Calculator"
    print "-" * 38
    print ""
    print "Options: "
    print "1. Degrees to Mils"
    print ""
    print "2. Mils to Degrees"
    print ""
    print "3. Quit"
    print "-" * 20
    print""
    return input ("Choose your option: ")
    print ""

#This function contains my attempt at rounding the sum and returns errors
def m2d(a):
    print "Enter azimuth in mils (ex. 6400)"
    b = 17.78
    c = a / b
    print a, " mils = ", c, "degrees"
    round(c[])

#This function works as intended but does not include round()
def d2m(b):
    print "Enter azimuth in degrees (ex. 90)"
    a = 17.78
    print b, " degrees = ", b * a, "mils"


loop = 1
choice = 0
while loop == 1:
    choice = menu()
    if choice == 1:
       d2m(input("Degrees: "))

    elif choice == 2:
        m2d(input("Mils: "))

    elif choice == 3:
        loop = 0
4

3 回答 3

2
>>> round(359.955)
360.0

def m2d(a):
    print "Enter azimuth in mils (ex. 6400)"
    b = 17.78
    c = round((a / b),0) #This would round the value to zero decimal places.
    print a, " mils = ", c, "degrees"

>>> m2d(6400)
Enter azimuth in mils (ex. 6400)
6400  mils =  360.0 degrees

有关 round() 的更多信息,请参阅:http ://docs.python.org/2/library/functions.html#round

如果您在打印时不想要小数位,您可以将替换cint(c).

此外,当您说 print var1,var2 时,它会自动在两者之间放置一个空格。您可能想尝试:

    print a, "mils =", c, "degrees"
于 2013-01-07T00:01:07.680 回答
1

您可以将浮点数作为变量传递。

round(c, 2)

会将 c 舍入到小数点后两位。

于 2013-01-07T00:01:27.633 回答
0

对于第 1 天的知识,您已经很好地理解了 python 的概念。现在,可以更改代码中的某些内容以使某些输入更容易,但修改起来非常简单:

c = a / b
c = round(c)

看起来您正在舍入变量而不更改变量本身,这就是导致问题的原因。

于 2013-01-07T00:03:49.270 回答