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

如何不使用Round()函数使平方根输出保留四位小数?

如何在不使用round()函数的情况下保留Python计算平方根结果的四位小数?

嘿,我来帮你搞定这个问题!不用round()函数的话,我们有几种简单靠谱的方法可以实现保留四位小数的需求,刚好匹配你的期望输出,下面给你详细说明:

方法1:字符串格式化(最推荐)

这是最直观且符合需求的方式,利用Python的字符串格式化语法,直接指定输出的小数位数,它会自动帮你完成四舍五入处理,完全不需要round()。

修改你的代码如下:

import math
n = int(input('Do you want to calculate the root of a few numbers? --> '))
for i in range(n):
    usrinp = int(input('Enter the number for root --> '))
    x = math.sqrt(usrinp)
    # 使用f-string格式化输出四位小数
    print(f"{x:.4f}")

你也可以用str.format()方法替代f-string,效果完全一样:

print("{:.4f}".format(x))

运行这段代码后,输入你给出的示例值,就能得到期望的输出:

1.0000
1.4142
1.7320
4.3588

方法2:数学运算模拟四舍五入

如果你想用纯数学的方式实现四舍五入(依然不用round()),可以通过放大数值、调整后再缩小的方式达成:

import math
n = int(input('Do you want to calculate the root of a few numbers? --> '))
for i in range(n):
    usrinp = int(input('Enter the number for root --> '))
    x = math.sqrt(usrinp)
    # 数学方法实现四舍五入到四位小数
    x_rounded = (x * 10000 + 0.5) // 1 / 10000
    # 搭配格式化确保输出四位小数格式
    print(f"{x_rounded:.4f}")

原理很简单:把数值乘以10000,让四位小数转化为整数部分;加0.5后取整(正数场景下//1等同于向下取整),就能实现四舍五入;最后除以10000还原数值。不过这种方法要注意浮点数精度问题,但对于你的使用场景完全够用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:21:22