Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the “narrower” type is widened to that of the other, where plain integer is narrower than long integer is narrower than floating point is narrower than complex. Comparisons between numbers of mixed type use the same rule.
这很容易测试。默认情况下,如果对两个整数执行算术运算,Python将结果存储为整数。你可以在这里看到。你知道吗
type函数将告诉您Python中对象的“type”是什么。在这里我们可以看到z变量的类型是int,它代表整数。你知道吗
如果我们对两种不同的类型执行算术,比如整数和浮点,结果是十进制,那么结果将存储为浮点。你知道吗
现在,如果对一个整数和一个浮点数执行算术,结果显示为非十进制,Python仍然会将其存储为一个浮点数。你可以在这里看到。你知道吗
总之,当您进行算术运算时,只有当所涉及的两个数字也是整数时,Python才会将结果存储为整数。如果一个是float,那么新变量也将是float类型(或类)。你知道吗
希望这有帮助:)
当混合类型时,总是会得到'wider'类型,其中复数比float宽,而float又比整数宽。当两个值都是同一类型(所以不是混合类型)时,只会得到一个类型作为结果。你知道吗
从Numeric Types documentation:
因此,当对不同类型的数字求和时,Python会将较窄的类型加宽,使其与较宽的类型相同。对于带有整数和浮点数的操作,您将得到一个float,因为float更宽。你知道吗
但是,如果两个操作数都是同一类型,则更改类型没有意义。在那种情况下改变类型将是非常令人惊讶的。你知道吗
例如:
如果浮点数或整数之间的差异对应用程序很重要,请显式地将用户输入转换为浮点数,以便您知道每次处理的是什么。你知道吗
相关问题 更多 >
编程相关推荐