Skip to main content
 首页 » 编程设计

python之如何更正此舍入功能

2025年05月04日11hnrainll

如何更正此舍入函数?

def round_down(num, prec): 
    uod = round(num, prec) 
    if uod > num: 
        return uod - 1/10^prec   
    return uod 

它引发:TypeError:^ 不支持的操作数类型:'float' 和 'int'。

请您参考如下方法:

^ 并不是你想的那样。使用 **相反。

From the Python documentation :

The ^ operator yields the bitwise XOR (exclusive OR) of its arguments, which must be plain or long integers.

此外,正如 mgilson 指出的那样,1/10 在 Python 2.x 中将等于 0,因此您想使用 1.0/10 改为:

def round_down(num, prec): 
    uod = round(num, prec) 
    if uod > num: 
        return uod - 1.0/10 ** prec   
    return uod