# -*- coding: utf-8 -*-
# 高精度计算器 v0.1b (Python 3.7)
from decimal import Decimal, getcontext
import re
import os

# 设置控制台颜色：黑底白字 (0x0F)
os.system('color 0F')

getcontext().prec = 30

def safe_calc(expr):
    # 只允许数字、+-*/()、空格、小数点
    if any(c not in '0123456789+-*/() .' for c in expr):
        raise ValueError("表达式无效")
    # 将数字字面量替换为 Decimal('数字')
    safe_expr = re.sub(r'\b\d+(?:\.\d+)?\b', lambda m: "Decimal('{}')".format(m.group()), expr)
    return eval(safe_expr, {"Decimal": Decimal}, {})

def format_result(result):
    s = str(result)
    if '.' in s:
        s = s.rstrip('0').rstrip('.')
    return s

def main():
    print("=======================计算器 v0.7b=======================")
    print("作者：eer4 | 2026年03月22日")
    print("基于 Python 3.7.0 + decimal 模块")
    print("现仅支持四则运算")
    print("输入“about”关于 | 输入“exit”退出")
    print("注意：一定要按“exit”退出，不然程序挂了后果自负！！！")
    print("      Python 2.4.0、2.5.2、2.6.3就是这样挂掉的！！！")
    print("==========================================================")

    while True:
        expr = input("\n>>> ").strip()
        if expr.lower() == 'exit':
            break
        elif expr.lower() == 'about':
            print("\n计算器 v0.1b")
            print("基于 Python 3.7.0 + decimal 模块")
            print("支持：加(+)、减(-)、乘(*)、除(/)")
            print("精确计算：如 0.1+0.2 = 0.3")
            continue
        if not expr:
            continue
        try:
            result = safe_calc(expr)
            out = format_result(result)
            print(out)   # 只输出结果数字
        except Exception as e:
            print("[错误] {}".format(e))

if __name__ == "__main__":
    main()
