四舍五入到小数点后2在python中gpa计算器



对于我的作业,我被要求创建一个GPA计算器。他们希望我编辑我的代码,使GPA输出总是显示两位小数。然而,我的似乎不工作!D:

输出只打印到小数点后1位

这是我到目前为止尝试过的,我也尝试过用str代替float:

gpa = total/num_of_subjects #using this formula the gpa is calculated
gpa = float(round(gpa, 2))
print (gpa) #output gpa

尝试将其格式化为只显示2位小数

gpa = total/num_of_subjects #using this formula the gpa is calculated
print(f"{gpa:.2f}")

您可以将输出格式为"{:0.2f}"格式的字符串值,因此尽管gpa值,您的答案将始终有2个十进制数字:

total, num_of_subjects = 100, 10
gpa = total/num_of_subjects
gpa = float(round(gpa, 2))
print("{:0.2f}".format(gpa))

10.00

您需要使用int来进行向上而不是向下的舍入。代码的另一个问题是,您使用num_of_subjects作为输入,但随后试图除以它。如果一个人选了3门课,那么他的gpa就会是0.0。下面是你应该如何修复它:

def calculateGPA():
total = float(input("Enter the number of units completed"))
num_of_subjects = float(input("Enter the number of courses taken"))
gpa = total / num_of_subjects
print ("The GPA is", gpa)
if gpa >= 4.0:
print ("Excellent")
elif gpa > 3.5 and <4.0:
print ("Very Good")
else :
print ("Good")
calculateGPA()
from decimal import Decimal

total = 109
num_of_subjects = 33
gpa = total/num_of_subjects #using this formula the gpa is calculated
gpcc= Decimal(gpa)
print(round(gpcc,2))

这里你有一个更简单的解决方案来解决同样的问题!干杯!