round 函数在 python 中不起作用
我如何舍入函数。
我在 python 中有以下代码
def round(x,n):
return round(x,n)
我收到以下错误
>>> round(3,98.9898, 2)
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
round(3,98.9898, 2)
TypeError: round() takes exactly 2 arguments (3 given)
我认为逗号正在造成问题
任何建议....请谢谢
我尝试过这个。
def round(x,n):
return round(float(x.replace(",", "")),n)
没有运气。
how do i round off a function.
i have the following code in python
def round(x,n):
return round(x,n)
i get the following error
>>> round(3,98.9898, 2)
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
round(3,98.9898, 2)
TypeError: round() takes exactly 2 arguments (3 given)
i think the comma is creating the problem
any suggestions.... please thanks
i tried this.
def round(x,n):
return round(float(x.replace(",", "")),n)
no luck.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
两个问题:
round(3,98.9898, 2)
是您输入的代码。自己省略逗号,您的问题就会消失。否则,请向我们提供有关您的问题的更多信息。def round(x, n): 返回 round(x, n)
即使您修复了函数调用,由于最大递归,您很可能会遇到
RuntimeError
。将函数重命名为round
以外的名称。Two issues:
round(3,98.9898, 2)
is code that you enter. Omit the comma yourself and your problem goes away. Otherwise give us more info about your problem.def round(x, n): return round(x, n)
Even if you fix your function call, you'll most likely end up with
RuntimeError
due to maximum recursion. Rename your function to something other thanround
.你是怎么得到这个号码的?如果是自动生成的,则它必须是一个字符串。当您使用
number
作为 round 的参数时,执行float(number.replace(',',''))
。How are you getting that number? If it autogenerated, it must be a string. do a
float(number.replace(',',''))
when you are using it thenumber
as an argument for round.是的,就是逗号。在 Python 中,要创建浮点数,您只需使用点。逗号还有很多其他作用!
编辑:你想做什么?你的号码是多少?
Yes, it is the comma. In Python to create floating point numbers you use only the point. Commas do many other things!
EDIT: What do you want to do? What is your number?
是的,就是逗号。数字中不能有逗号。逗号只能用于显示目的,在所有计算之后添加,这可以在将数字转换为字符串之后完成。
如果您正在处理用户输入,它将是一个字符串,并且在转换为 float/int 之前您必须删除逗号。
我要退后一步,从基础开始。这是你的实际代码吗?
如果是这样,您将向函数传递三个参数:
3
、98.9898
和2
,但该函数只接受两个。也许您的意思是以下之一:或其他一些变体?
Yes, it's the comma. A number cannot have a comma in it. Commas should only be added for display purposes, after all computation, which can be done after converting the number to a string.
If you're dealing with user input, it's going to be a string, and you'll have to strip out commas before converting to a float/int.
I'm gonna step back and start with the basics. Is this your actual code?
If so, you are passing three parameters into the function:
3
,98.9898
, and2
, but the function only accepts two. Perhaps you mean one of the following:or some other variation?