为什么会发生?

发布于 2025-02-08 12:50:21 字数 346 浏览 1 评论 0原文

因此,我已经启动了一个程序来计算一个数字的第n个词:

*x = float(input('Enter a number: '))
n = float(input('Enter the root you would like to calculate: '))
result=x**(1/float(n))
print(f'The {n}th root of = {x} is:',result)*

该程序可与每个数字和根一起使用,但是当我输入x = 64和n = 3时,它显示了以下内容: 3.0 = 64.0的根是:3.9999999999999996

So, I've started a program to calculate the nth root of a number:

*x = float(input('Enter a number: '))
n = float(input('Enter the root you would like to calculate: '))
result=x**(1/float(n))
print(f'The {n}th root of = {x} is:',result)*

The program works with every number and root, but when I enter as x=64 and n=3 it shows this:
The 3.0 root of = 64.0 is: 3.9999999999999996

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眼泪都笑了 2025-02-15 12:50:21

如评论中所述,这是浮点数学的性质。

就您而言,您可以在F弦中使用指定符来控制您的打印内容:

>>> n = 3.999996
>>> print(f"{n : .0f}")
 4
>>> 

As noted in comments, this is the nature of floating point math.

In your case, you can control what you print with a specifier in an f-string:

>>> n = 3.999996
>>> print(f"{n : .0f}")
 4
>>> 
三生路 2025-02-15 12:50:21

它是因为浮点被存储的方式。通常,您会看到这样的东西,一个解决方案是始终将结果归结为最近的千分之一。

Its because of the way floating point is stored. Often you'll see stuff like this, a solution is to always round result to the nearest like, thousandth.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文