首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Modulo未正确处理

Modulo未正确处理
EN

Stack Overflow用户
提问于 2013-04-22 01:10:36
回答 1查看 118关注 0票数 0

我似乎不能确保python的取模函数工作正常,我尝试了各种数字,但似乎无法得到正确的划分。

ISBN号

代码语言:javascript
复制
print """
Welcome to the ISBN checker,

To use this program you will enter a 10 digit number to be converted to an International Standard Book Number

"""

ISBNNo = raw_input("please enter a ten digit number of choice") 


counter = 11 #Set the counter to 11 as we multiply by 11 first
acc = 0 #Set the accumulator to 0

开始循环,将字符串中的每个数字乘以描述计数器。我们需要将数字视为字符串,以获得每个位置

代码语言:javascript
复制
for i in ISBNNo: 
    print str(i) + " * " + str(counter)
    acc = acc + (int(i) * counter) #cast value a integer and multiply by counter
    counter -= 1 #decrement counter
print "Total = " + str(acc)                   

模数除以11 (除以余数

代码语言:javascript
复制
acc = acc % 11
print "Mod by 11 = " + str(acc)

从11开始

代码语言:javascript
复制
acc = 11 - acc
print "subtract the remainder from 9 = " + str(acc)

与字符串连接

代码语言:javascript
复制
ISBNNo = ISBNNo + str(acc)
print "ISBN Number including check digit is: " + ISBNNo
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-04-22 01:26:04

您的代码大部分都是正确的,除了一些问题:

1)如果ISBN,您正在尝试计算校验和(最后一位)。这意味着您应该只考虑9位数:

代码语言:javascript
复制
ISBNNo = raw_input("please enter a ten digit number of choice") 
assert len(ISBNNo) == 10, "ten digit ISBN number is expected"
# ...
for i in ISBNNo[0:9]: # iterate only over positions 0..9 
    # ...

2)这里还应该有一个特例:

代码语言:javascript
复制
ISBNNo = ISBNNo + str(acc)
print "ISBN Number including check digit is: " + ISBNNo

您正在进行模11运算,因此acc可以等于10。ISBN要求使用"X“作为本例中的最后一个”数字“,可以写成:

代码语言:javascript
复制
ISBNNo = ISBNNo + (str(acc) if acc < 10 else 'X')

以下是修复后的代码,其中包含示例number from Wikipediahttp://ideone.com/DaWl6y

回应评论

代码语言:javascript
复制
>>> 255 // 11               # Floor division (rounded down)
23
>>> 255 - (255//11)*11      # Remainder (manually)
2
>>> 255 % 11                # Remainder (operator %)
2

(注意:我使用的是//,它代表地板分割。在Python2中,您也可以简单地使用/,因为您要除以整数。在Python3中,/始终是真除法,而//是地板除法。)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16133897

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档