不用库,写了很久,一直出bug,到网上一搜,可以直接输入之后,eval(str)即可得到结果!
eval程序如下:
1
2
|
print ( "The result is{}" . format ( eval (s)))
|
下面是不用eval实现加减的代码:主要思想就是通过一个标志位flag来计算是否进行加减,其他的都很好理解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
s = input ( "请输入要运算的数字" )
l = len (s)
h = 0
i = 0
flag = 1
a = 0
for i in range ( 0 ,l):
if s[i] = = '+' or s[i] = = '-' :
flag = 1
c = s[i]
else :
flag = 0
a = a * 10 + round ( int (s[i]))
if flag = = 1 and s[i] = = '+' :
h + = a
a = 0
elif flag = = 1 and s[i] = = '-' :
h - = a
a = 0
print (h)
|
现在贴上一直出错的代码,也算是长点经验,提醒自己下一次细心一点:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
s = input ( "请输入要运算的数字" )
l = len (s)
h = 0
i = 0
while i< = l:
a = 0
c = s[i]
i + = 1
while s[i]! = '+' and s[i]! = '-' and i< = l :
a = a * 10 + round ( int (s[i]))
i + = 1
if c = = '+' :
h + = a
else :
h - = a
print (h)
|
1
|
#错误类型:IndexError: string index out of range(字符串越界)
|
说明一下,越界有两个原因:
①能够访问的最大字符串是len(str)-1 (ps上图直接是len(str))
②python执行的方法是一句一句执行的,所以i<=l-1应该放在s[i] != '+'的前面
下面贴上修改过后能运行并且可以输出正确结果的代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
s = input ( "请输入要运算的数字" )
l = len (s) - 1
h = 0
i = 0
while i< = l:
a = 0
c = s[i]
i + = 1
while i< = l and s[i]! = '+' and s[i]! = '-' :
a = a * 10 + round ( int (s[i]))
i + = 1
if c = = '+' :
h + = a
else :
h - = a
print (h)
|
以上这篇python实现输入数字的连续加减方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/Pain_Love/article/details/74572089