You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中对测验百分比进行取整(保留0位小数)

解决方法

有几种简单的方式可以让你的百分比显示为整数:

1. 使用round()函数

你提到的round函数用法很直接:第一个参数是要处理的数值,第二个参数是保留的小数位数。要保留0位小数,代码可以改成这样:

print("You got " + str(round((score / 3) * 100, 0)) + "%.")

运行后,33.333...会变成33,66.666...会变成67,满分就是100。

2. 使用f-string格式化(推荐)

Python 3.6及以上版本支持f-string,写法更简洁直观,直接在字符串里指定格式:

print(f"You got {(score / 3) * 100:.0f}%.")

这里:.0f表示把数值格式化为0位小数的浮点数,效果和round一致,但代码可读性更强。

3. 使用str.format()方法

如果用的是更早的Python版本,可以用这种方式:

print("You got {:.0f}%.".format((score / 3) * 100))

格式逻辑和f-string一样,只是写法不同。

修改后的完整代码片段

answer = input("What's my favorite pizza? ")
if answer.lower() == "4 cheese":
    print("Correct! Nice job!")
    score += 1
else:
    print("Incorrect, sorry man!")

print("You got " + str(score) + " questions correct!")
# 替换成f-string写法的打印语句
print(f"You got {(score / 3) * 100:.0f}%.")

这样输出就会变成You got 33%.或者You got 67%.这类整数百分比了。

内容的提问来源于stack exchange,提问作者pythonpyro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 18:51:02