gpt4 book ai didi

python - 如何让我的百分比输出为两位数?

转载 作者:行者123 更新时间:2023-12-05 01:49:41 24 4
gpt4 key购买 nike

我试图从这行代码中获得一个干净的百分比。例如,50.00% 或 61.37%。从这一行,我得到 5000.00% 等等。我有一个想法,它与我如何使用 format 有关,但我不确定它是如何做到这一点的。我尝试使用 int 并获得了所需的数字,只是没有 .00 和 % 符号。

class_males = float(input('Please enter the number of male students registered:')) #Asks for user input of males
class_females = float(input('Please enter the number of female students registered:'))#Asks for user input of females
class_total = int(class_males) + int(class_females) #class total by combining user inputs
m_perc = int(class_males)/int(class_total)* 100 #divide user input of males by class total then multiply by 100 for %
f_perc = int(class_females)/int(class_total)* 100 #divide user input of females by class total then multiply by 100 for %
male_perc = "{:.2%}".format(m_perc) #adds "%" sign after number total
female_perc = "{:.2%}".format(f_perc) #adds "%" sign after number total
print('Percentage of males registered:', (male_perc)) #display percent of males
print('Percentage of females registered:',(female_perc)) #display percent of females

如果还不清楚,我是初学者。感谢您提供的任何帮助。

最佳答案

您乘以 100 两次,因为 % 格式说明符已经为您完成了,但是您自己做了,导致最后乘以 10,000。

参见 docs :

Type Meaning
'%' Percentage. Multiplies the number by 100 and displays in fixed ('f') format, followed by a percent sign.

(强调我的。)

因此,产生最精简代码的解决方案是删除您自己乘以 100 并直接传递比率值:

m_ratio = int(class_males) / int(class_total) # divide user input of males by class total
f_ratio = int(class_females) / int(class_total) # divide user input of females by class total
male_perc = "{:.2%}".format(m_ratio) # multiplies by 100 and adds "%" sign after number total
female_perc = "{:.2%}".format(f_ratio) # multiplies by 100 and adds "%" sign after number total

或者,您可以使用 f 将格式转换为 float ,如 Claudio's answer 中所述。 .

关于python - 如何让我的百分比输出为两位数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73773616/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com