我们正在从包含整数的文件中读取行。正在读取的行数不确定。我们必须将每个整数拆分为整数的数字,然后将这些数字相加并创建另一个文件,其中写入该整数以及每个整数的数字之和。
教授说要使用事件控制循环,但除此之外没有具体说明。我们只被允许使用while
循环,不for
loops.
我不知道如何将代码放在这里,以便我可以展示到目前为止我所测试的内容,只是为了重新熟悉整数中一定数量的数字的分割。
编辑添加:
myFile = open("cpFileIOhw_digitSum.txt", "r")
numbers = 1
numberOfLines = 3
digitList = []
while(numbers <= numberOfLines):
firstNum = int(myFile.readline())
while (firstNum != 0):
lastDigit = firstNum % 10
digitList.append(lastDigit)
firstNum = firstNum / 10
firstDigit = firstNum
digitList.append(firstDigit)
digitSum = sum(digitList)
print digitList
print digitSum
numbers += 1
myFile.close()
^这是我到目前为止所拥有的,但现在我的问题是我需要将每个整数的数字存储在不同的列表中。这是从文件中读取的不确定数量的整数。用于计数和结束循环的数字只是示例。
我的代码的最新更新:几乎我现在需要知道的是如何让while
循环知道 txt 文件中没有更多行了。
myFile = open("cpFileIOhw_digitSum.txt", "r")
myNewFile = open("cpFileIOhw_output.txt", "w")
total = 0
fullInteger =
while(fullInteger != 0):
fullInteger = int(myFile.readline())
firstNum = fullInteger
while (firstNum != 0):
lastDigit = firstNum % 10
total = total + lastDigit
firstNum = firstNum / 10
firstDigit = firstNum
total = total + firstDigit
myNewFile.write(str(fullInteger) + "-" + str(total))
print " " + str(fullInteger) + "-" + str(total)
total = 0
myFile.close()
myNewFile.close()
嗯,有两种方法可以解决这个问题:
将整数转换为字符串并迭代每个字符,将每个字符转换回 int (最好使用for
loop)
-
重复得到整数除以10的被除数和模;重复直到股息为 0(最好用while
loop).
这些是您需要的数学运算符:
mod = 123 % 10 # 3
div = 123 // 10 # 12
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)