巨大数四则运算简单代码
时间: 2024-09-26 12:04:46 浏览: 34
在处理巨大数的四则运算时,通常会使用高精度算法,比如大整数库或内置支持大数的编程语言特性。这里以Python为例,它有一个内建的`decimal`模块可以方便地进行高精度计算。
```python
from decimal import Decimal
def add_large_numbers(num1, num2):
return str(Decimal(num1) + Decimal(num2))
def subtract_large_numbers(num1, num2):
return str(Decimal(num1) - Decimal(num2))
def multiply_large_numbers(num1, num2):
return str(Decimal(num1) * Decimal(num2))
def divide_large_numbers(num1, num2):
try:
return str(Decimal(num1) / Decimal(num2))
except ZeroDivisionError:
return "除数不能为零"
# 示例
num1 = '12345678901234567890'
num2 = '98765432109876543210'
print(add_large_numbers(num1, num2)) # 输出加法结果
print(subtract_large_numbers(num1, num2)) # 输出减法结果
print(multiply_large_numbers(num1, num2)) # 输出乘法结果
print(divide_large_numbers(num1, num2)) # 输出除法结果
阅读全文