编写一个程序,输入两个数字的加减乘除余数(Python版)

编写一个程序,输入两个数字的加减乘除余数

方法一:直接打印结果

python 复制代码
a = 15
b = 4
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a % b)

方法二:预先计算并存储结果到变量

python 复制代码
a = 15
b = 4
# 将运算结果存储到变量中
sum_result = a + b
diff_result = a - b
product_result = a * b
division_result = a / b
modulus_result = a % b
# 打印结果
print(sum_result)      # 19
print(diff_result)     # 11
print(product_result)  # 60
print(division_result) # 3.75
print(modulus_result)  # 3

方法三:使用 f-string (格式化字符串字面值) 进行格式化输出

python 复制代码
a = 15
b = 4

# 使用 f-string 格式化输出
print(f"{a} + {b} = {a + b}") # 15 + 4 = 19
print(f"{a} - {b} = {a - b}") # 15 - 4 = 11
print(f"{a} * {b} = {a * b}") # 15 * 4 = 60
print(f"{a} / {b} = {a / b}") # 15 / 4 = 3.75
print(f"{a} % {b} = {a % b}") # 15 % 4 = 3

方法四:使用 .format() 方法进行格式化输出

python 复制代码
a = 15
b = 4

# 使用 .format() 方法格式化输出
print("{} + {} = {}".format(a, b, a + b)) # 15 + 4 = 19
print("{} - {} = {}".format(a, b, a - b)) # 15 - 4 = 11
print("{} * {} = {}".format(a, b, a * b)) # 15 * 4 = 60
print("{} / {} = {}".format(a, b, a / b)) # 15 / 4 = 3.75
print("{} % {} = {}".format(a, b, a % b)) # 15 % 4 = 3

方法五:使用 % 操作符进行格式化输出 (较旧的方法)

python 复制代码
a = 15
b = 4

# 使用 % 操作符格式化输出
print("%d + %d = %d" % (a, b, a + b))   # 15 + 4 = 19
print("%d - %d = %d" % (a, b, a - b))   # 15 - 4 = 11
print("%d * %d = %d" % (a, b, a * b))   # 15 * 4 = 60
print("%d / %d = %.2f" % (a, b, a / b)) # 15 / 4 = 3.75 (保留两位小数)
print("%d %% %d = %d" % (a, b, a % b))  # 15 % 4 = 3 (注意 % 需要转义为 %%)

总结:

方法一适用于快速输出结果。

方法二 适用于你需要在后续代码中重复使用这些计算结果的情况。

方法三 (f-string) 是 Python 3.6+ 推荐的、最现代和最易读的格式化方法,非常推荐使用。

方法四 (.format()) 功能强大,兼容性较好(适用于 Python 2.7 及以上),但写法稍长。

方法五 (% 操作符) 是比较古老的方法,现在一般不推荐使用,除非需要兼容非常旧的 Python 版本。

相关推荐
devmoon几秒前
在 Paseo 测试网上获取 Coretime:On-demand 与 Bulk 的完整实操指南
开发语言·web3·区块链·测试用例·智能合约·solidity
皮卡丘不断更8 分钟前
手搓本地 RAG:我用 Python 和 Spring Boot 给 AI 装上了“实时代码监控”
人工智能·spring boot·python·ai编程
kylezhao201917 分钟前
C# 中的 SOLID 五大设计原则
开发语言·c#
爱打代码的小林24 分钟前
基于 MediaPipe 实现实时面部关键点检测
python·opencv·计算机视觉
极客小云42 分钟前
【ComfyUI API 自动化利器:comfyui_xy Python 库使用详解】
网络·python·自动化·comfyui
凡人叶枫1 小时前
C++中输入、输出和文件操作详解(Linux实战版)| 从基础到项目落地,避坑指南
linux·服务器·c语言·开发语言·c++
闲人编程1 小时前
Elasticsearch搜索引擎集成指南
python·elasticsearch·搜索引擎·jenkins·索引·副本·分片
春日见1 小时前
车辆动力学:前后轮车轴
java·开发语言·驱动开发·docker·计算机外设
痴儿哈哈1 小时前
自动化机器学习(AutoML)库TPOT使用指南
jvm·数据库·python
锐意无限1 小时前
Swift 扩展归纳--- UIView
开发语言·ios·swift