繁体   English   中英

简单的数学加法

[英]Simple math addition

所以我只想做一些简单的数学加法从第一个文件中获取数字(假设它是 1)和第二个文件中的数字(假设它是 2)所以我得到的是 12,而不是 3 我真的很感激帮助。

myfile = open('file.txt', "r")
onecaracter = myfile.read(2)
with open('liczba1.txt', 'w') as f:
print(onecaracter, file=f)

myfile = open('file.txt', "r")
twocaracter = myfile.read(myfile.seek(4))

with open('liczba22.txt', 'w') as f:
print(twocaracter, file=f)

with open('liczba1.txt', "r") as file:
z = file.read(1)

with open('liczba22.txt', "r") as fil:
b = fil.read(1)

print(z + b)

变量zb可能是str类型,并且+运算符在str类型上定义为连接。 您可以将这两个变量转换为整数,它们应该按照您的预期添加,即:

print(int(z) + int(b))

为了说明这一点,您始终可以打印出变量的类型:

print(type(z))
myfile = open('file.txt', "r")
onecaracter = myfile.read(2)
with open('liczba1.txt', 'w') as f:
print(onecaracter, file=f)

myfile = open('file.txt', "r")
twocaracter = myfile.read(myfile.seek(4))

with open('liczba22.txt', 'w') as f:
print(twocaracter, file=f)

with open('liczba1.txt', "r") as file:
z = file.read(1)

with open('liczba22.txt', "r") as fil:
b = fil.read(1)

print(int(z) + int(b))

你应该做一个类型转换:

total = int(z) + int(b)
print(total)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM