更改非正数除法的 python 数学模块行为
非正数除法在 C++ 和 Python 编程语言中非常不同:
//c++:
11 / 3 = 3
11 % 3 = 2
(-11) / 3 = -3
(-11) % 3 = -2
11 / (-3) = -3
11 % (-3) = 2
(-11) / (-3) = 3
(-11) % (-3) = -2
因此,如您所见,C++ 正在最小化商。 然而,python 的行为是这样的:
#python
11 / 3 = 3
11 % 3 = 2
(-11) / 3 = -4
(-11) % 3 = 1
11 / (-3) = -4
11 % (-3) = -1
(-11) / (-3) = 3
(-11) % (-3) = -2
我无法编写自己的除法函数,其行为类似于 c++,因为我将使用它来检查 c++ 计算器程序,并且 python 不支持中缀运算符。我可以让 python 的行为像 c++ 一样,同时以简单的方式除以整数吗?例如,设置一些标志或类似的东西?
Non-positive number division is quite different in c++ and python programming langugages:
//c++:
11 / 3 = 3
11 % 3 = 2
(-11) / 3 = -3
(-11) % 3 = -2
11 / (-3) = -3
11 % (-3) = 2
(-11) / (-3) = 3
(-11) % (-3) = -2
So, as you can see, c++ is minimizing quotient.
However, python behaves like that:
#python
11 / 3 = 3
11 % 3 = 2
(-11) / 3 = -4
(-11) % 3 = 1
11 / (-3) = -4
11 % (-3) = -1
(-11) / (-3) = 3
(-11) % (-3) = -2
I can't code my own division function behaving like c++, because I'll use it for checking c++ calculator programs, and python does not support infix operators. Can I make python behaving like c++ while dividing integers in a simple way? For example, setting some flag or something like that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如 Thomas K 所说,使用
math.fmod
进行取模,或者如果您确实想要,您可以自己定义它:并且此函数应该模拟 C 风格的除法:
您说过您必须 使用
/
和%
运算符。这是不可能的,因为您无法覆盖内置运算符。不过,您可以定义自己的整数类型和运算符重载__div__
和__mod__
运算符。As Thomas K said, use
math.fmod
for modulo, or if you really want you can define it yourself:And this function should emulate C-style division:
You said that you must use the
/
and%
operators. This is not possible, since you can't override the operator for built-ins. You can however define your own integer type and operator overload the__div__
and__mod__
operators.没有可以设置的标志来使 python 除法像 c++ 一样。
您建议您不能编写自己的除法函数,但如果您改变主意,您可以这样做:
这表明它按照您的规范行事:
这给出了:
There is no flag you can set to make python division to act like c++.
You advised that you can't code your own division function, but if you change your mind you can do this:
This shows that it acts according to your specification:
Which gives:
您还应该查看标准库中的 decimal 模块。
然而,结果
You should also check out the decimal module from standard library.
Yet, the result of