如何配置我的数组以小数为单位执行考虑数?

2024-06-02 19:59:16 发布

您现在位置:Python中文网/ 问答频道 /正文

# input a string 
str = input("Enter the expression: ")
# make an array to check the operator
opArr = ["+","-","*","/"]
# check for operator 
op = ""
for operator in opArr:
    if str.find(operator) == 1:
        op = operator
# split the array
splitStr = str.split(op)
print(splitStr)
# perform mathematical operations
if op == "+":
    result = float(splitStr[0]) + float(splitStr[1])
elif op == "-":
    result = float(splitStr[0]) - float(splitStr[1])
elif op == "*":
    result = float(splitStr[0]) * float(splitStr[1])
elif op == "/":
    result = float(splitStr[0]) / float(splitStr[1])
else:
    result = "Something Went Wrong!!!"

print(result)

这里的输出是: 输入表达式:5+5//works输出为10

但当我输入5.0+5或任何其他十进制数时,它会打印出一个错误

我可以看出split()方法将字符串转换为字符数组的问题。有没有一种方法可以将其转换为字符串数组或任何其他方法来保存类似[“5.0”,“5”]这样的元素,以便5.0+5的输出为10.0


Tags: the方法forinputcheckresultfloatarray
3条回答

只需修改for循环。如果未找到子字符串,则Tipsstr.find返回-1

for operator in opArr:
    if str.find(operator) != -1: ## t
        op = operator

str.find(运算符)返回运算符的位置。我建议将条件替换为if str.find(operator)>;0:

# input a string
str = input("Enter the expression: ")
# make an array to check the operator
opArr = ["+", "-", "*", "/"]
# check for operator
op = ""
for operator in opArr:
    if str.find(operator)>0:
        op = operator
# split the array
splitStr = str.split(op)
print(splitStr)
# perform mathematical operations
if op == "+":
    result = float(splitStr[0]) + float(splitStr[1])
elif op == "-":
    result = float(splitStr[0]) - float(splitStr[1])
elif op == "*":
    result = float(splitStr[0]) * float(splitStr[1])
elif op == "/":
    result = float(splitStr[0]) / float(splitStr[1])
else:
    result = "Something Went Wrong!!!"

print(result)

docs开始:

Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

问题是在5.0+5期间,运算符+出现在第三个索引位置。但是3不等于1。因此op保持不变。而且split需要一些分隔符,它可以在这些分隔符上拆分字符串

您可以在这里使用in运算符,如果在主字符串中找到特定的子字符串,该运算符将返回True

for operator in opArr:
    if operator in str1:
        op = operator

相关问题 更多 >