长算式加减计算器开发求助:优化文本文件读取运算逻辑
Hey, let's get this sorted out! The core issue with your current code is that it only executes the first operation and stops—we need to loop through every operator and number in the formula to compute the final result properly. Here's a straightforward, step-by-step solution (I'll use Python since it natively supports arbitrary-length integers, which fits your requirement perfectly):
Step 1: Read the formula from file
First, we'll load the content of formula.txt and clean up any extra whitespace:
with open('formula.txt', 'r') as file: formula = file.read().strip()
Step 2: Parse the formula into tokens
Split the formula string into a list of numbers and operators. For example, "100 + 50 - 25" becomes ["100", "+", "50", "-", "25"]:
tokens = formula.split()
Step 3: Iterate through all operations to compute the result
Initialize the result with the first number, then loop through each subsequent operator-number pair to update the result:
# Handle edge case: formula is just a single number if len(tokens) == 1: result = int(tokens[0]) else: result = int(tokens[0]) # Step through tokens 2 at a time (operator + number) for i in range(1, len(tokens), 2): op = tokens[i] num = int(tokens[i+1]) if op == '+': result += num elif op == '-': result -= num else: # Throw an error if an unsupported operator is found raise ValueError(f"Unsupported operator: {op}") print(f"Final result: {result}")
Key Notes:
- Arbitrary-length integers: Python's
inttype can handle numbers of any size, so you don't have to worry about overflow issues with very large numbers. - Edge case handling: The code checks if the formula is just a single number (no operators) and returns it directly.
- Error handling: It raises a clear error if an unexpected operator is present, making debugging easier.
Testing this with your example "100 + 50 - 25" will correctly output 125 instead of stopping at 150. You can extend this further if needed (like handling multiple lines in formula.txt), but this core logic will fix your current problem.
内容的提问来源于stack exchange,提问作者MLWeegee

