2017-02-09 166 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