2017-02-09 163 views
0

我需要在我的程序中有一段代码,它将在我的代码中获得一个数字“dSum”,并将其向上移动,最接近的十位。例如,如果dSum是33,我需要dSumRounded为40.我已经拥有的代码行是错误的,它似乎将下调到最近的十位。我发现从另一个stackoverflow问题的代码片段,但它只是不在这种情况下工作。将数字四舍五入到最接近的十位

import math #Imports the math library 

def findCheckDigit(): 
    code = input("Please enter your 7 digit code: ") #Makes a function and sets the code to a variable 

    d1 = int(code[0]) * 3 
    d2 = int(code[1]) * 1 
    d3 = int(code[2]) * 3 
    d4 = int(code[3]) * 1 #Seperates each digit and assigns it to a variable, multiplying it by 3 or 1 
    d5 = int(code[4]) * 3 
    d6 = int(code[5]) * 1 
    d7 = int(code[6]) * 3 

    dSum = d1 + d2 + d3 + d4 + d5 + d6 + d7  #Adds each digit together 
    dSumRounded = int(math.ceil(dSum/10.0)) * 10 #Gets the rounded up version of the sum of the digits 
    checkDigit = dSumRounded - dSum #Makes the check digit equal to the sum of digits taken away from the rounded up sum of digits 

    print(dSumRounded) 
    print("Your check digit is: " + str(checkDigit)) #Prints the check digit 
+2

我试过了,它的工作原理(33被四舍五入为40) – BlackBear

+0

所有的数字都加起来了,31也是40吗? – depperm

+0

好的,我注意到了这个问题。我尝试了其他7位数字代码,但它是2222222由于某种原因返回0。在某个地方似乎有问题,但我很难过。 –

回答

1

我宁愿留在整数域。

>>> for i in range(20, 40): 
     print(i, '->', (i + 9) // 10 * 10) 

20 -> 20 
21 -> 30 
22 -> 30 
23 -> 30 
24 -> 30 
25 -> 30 
26 -> 30 
27 -> 30 
28 -> 30 
29 -> 30 
30 -> 30 
31 -> 40 
32 -> 40 
33 -> 40 
34 -> 40 
35 -> 40 
36 -> 40 
37 -> 40 
38 -> 40 
39 -> 40 

这就是说,你自己的表达int(math.ceil(dSum/10.0)) * 10作品了。

+0

这将与整数类型一起工作,但您会遇到浮点类型的困扰。 – Bathsheba

+0

对。不过,他们的数字是整数。 –

+0

只是说';-)一个早期的Java实现过去常常用于四舍五入,带来灾难性后果。 – Bathsheba