20224102段浩楠《Python程序设计》实验二报告
课程:《Python程序设计》
班级: 2241班
姓名: 段浩楠
学号:20224102
实验教师:王志强
实验日期:2024年3月26日
必修/选修: 公选课
1.实验内容
设计并完成一个完整的应用程序,完成加减乘除模等运算,功能多多益善。
#caculator
import math
def sum (a,b):
return(a+b)
def sub (a,b):
return(a-b)
def mul (a,b):
return(a*b)
def div (a,b):
if b == 0:
print("o不能")
return 0
return(a/b)
def csum (c1,c2):
return c1+c2
def csub (c1,c2):
return c1-c2
def cmul (c1,c2):
return c1*c2
def cdiv (c1,c2):
return c1/c2
#对数
def log(a,b):
return math.log(b,a)
#加一个循环重复运算
flag = True
while flag:
# 这里可以加一些修饰input....
print(''' 欢迎使用简单计算器
制作人:20224102段浩楠
制作时间2024/3/26
开始计算吧''')
operator=input("请输入运算符号(+、-、*、/、c、log")
if operator == "+":
a = int(input("请输入a="))
b = int(input("请输入b="))
#int(input("xxx"))=eval(input("xxx")
print("a+b=",sum(a,b))
elif operator == "-":
a = int(input("请输入a="))
b = int(input("请输入b="))
print("a-b=",sub(a,b))
elif operator == "*":
a = int(input("请输入a="))
b = int(input("请输入b="))
print("a*b=", mul(a, b))
elif operator == "/":
a = int(input("请输入a="))
b = int(input("请输入b="))
print("a/b=", div(a, b))
elif operator == "c":
coperator = input("请输入复数的运算+-*、:")
c1 = eval(input("请输入复数1(eg:1+2j):"))
c2 = eval(input("请输入复数2(eg:1+2j):"))
#复数运算
if coperator == "+":
print("(",c1,")+(",c2,")=", csum(c1,c2))
elif coperator == "-":
print("(",c1,")-(",c2,")=", csub(c1,c2))
elif coperator == "*":
print("(", c1, ")*(", c2, ")=", cmul(c1, c2))
elif coperator == "/":
print("(", c1, ")/(", c2, ")=", cdiv(c1, c2))
elif operator == "log":
a = eval(input("请输入a:"))
b = int(input("请输入b:"))
print("logab=", log(a, b))
flag= True if eval("是否继续游戏?Y or N")== "Y" else False
使用def关键字定义函数1,并通过函数名加括号来调用函数。
条件语句:使用if elif else来根据条件执行不同的代码块。
输入输出:使用input函数来获取数据输入,使用print函数来输出结果
循环语句:使用while循环来重复执行代码块,直到条件不符。
2. 实验过程及结果
3. 实验过程中遇到的问题和解决过程
(1)复数输入格式错误
在输入复数时,我忘记添加虚部的‘j'导致无法输出结果
解决方式是在获取用户输入后,使用异常处理机制来处理错误的输入格式
(2)log函数无法使用
解决方法:引用前,导入math函数。
4.心得体会
无限小数因为十进制与二进制的浮点数原因导致误差。
条件语句和循环语句: 条件语句和循环语句是控制程序流程的重要工具。在编写以上代码时,我运用了条件语句 if-elif-else 和循环语句 while,以根据不同的条件执行相应的代码块,实现了计算器的基本功能。