阿摩線上測驗 登入

申論題資訊

試卷:100年 - 100年高等三級暨普通考普通_資訊處理#29521
科目:程式設計
年份:100年
排序:0

題組內容

一、請設計一程式,在輸入一個正整數四則運算式(只有加、減、乘、除四種運算,不 含括號)後,計算運算式並將結果輸出。假設所有運算一律採由左至右順序運算。 請注意:

申論題內容

⑵進行除法運算只取整數結 果,若無法整除時採捨去小數方式。例如:輸入整數四則運算式:121*3/2,計算結 果為 181。(25 分)

詳解 (共 1 筆)

詳解 提供者:hchungw
這是一個簡單的解析器,它會根據由左至右的規則計算四則運算的結果,當進行除法時,它會捨去任何小數位數來只取整數結果。以下是該解析器的 Python 實現:
python
Copy code
def simple_calculator(expression):
    # Initial total is the first number in the expression
    elements = expression.split()
    total = int(elements[0])
    
    # Process the rest of the expression
    i = 1
    while i < len(elements):
        operator = elements[i]
        number = int(elements[i + 1])
        if operator == '+':
            total += number
        elif operator == '-':
            total -= number
        elif operator == '*':
            total *= number
        elif operator == '/':
            total //= number  # Use floor division to get an integer result
        
        i += 2  # Move past the operator and number
    return total
# Example usage:
# expression = input("Enter an expression: ")
# result = simple_calculator(expression)
# print("The result is:", result)
# Since we cannot get user input in this environment, let's use the given example
example_expression = "121 * 3 / 2"
result = simple_calculator(example_expression.replace('*', ' * ').replace('/', ' / '))
print("The result is:", result)