【问题标题】:The output returns in string format and not int. Eg: the function returns "1563.7383" instead of 1563.7383输出以字符串格式返回,而不是 int。例如:函数返回“1563.7383”而不是 1563.7383
【发布时间】:2019-02-04 20:29:53
【问题描述】:
def polysum(n,s):
    import math
    r = math.pi/n
    area = ((0.25)*n*(s**2))/ math.tan(r)
    per = n*s
    total = area + (per**2)
    return ("%.4f" % total)

输出以字符串格式返回,而不是 int。例如:函数返回“1563.7383”而不是1563.7383

【问题讨论】:

  • 在询问与代码相关的问题时,为该语言添加标签总是一个好主意。你可以edit 这样做吗?当您使用它时,您还可以努力格式化您的代码(选择它,然后按 Ctrl+K 或工具栏上的 {} 按钮)以便它可读。谢谢。 :-)

标签: output-formatting


【解决方案1】:

您没有在问题中添加语言标签,但从语法来看,我认为这里是 Python。

首先请注意,1563.7383 不能int,但可以是float

您的问题在于您对"%.4f" % total 的使用,它将total 转换为具有4 个小数位的字符串。

您可能应该只在函数中返回total(即在整个程序中将其视为float,不进行四舍五入)。只有在实际输出值时才使用"%.4f" % total 将其四舍五入。

或者,如果您绝对必须对函数中的值进行四舍五入并将其作为float,请考虑改用内置函数round()。那么你的用法就是return round(total, 4)

【讨论】:

    猜你喜欢
    • 2019-09-15
    • 2015-03-03
    • 2016-05-28
    • 2022-01-12
    • 2013-05-16
    • 1970-01-01
    • 2014-07-28
    • 1970-01-01
    • 2018-11-16
    相关资源
    最近更新 更多