本文介绍了Python样式整数除法和放大器;模用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python和Ruby,签署整数除法向负无穷截断,并有符号的整数模量具有相同的标志第二个操作数:

In Python and Ruby, signed integer division truncates towards negative infinity, and signed integer modulus has the same sign the second operand:

>>> (-41) / 3
-14
>>> (-41) % 3
1

不过,在C和Java,签署整数除法向0截断,并有符号的整数模量具有相同的符号作为第一个操作数:

However, in C and Java, signed integer division truncates towards 0, and signed integer modulus has the same sign as the first operand:

printf("%d\n", (-41) / 3); /* prints "-13" */
printf("%d\n", (-41) % 3); /* prints "-2" */

什么是用C来执行相同类型的划分和模量在Python和Ruby最简单,最有效的方法是什么?

What is the simplest and most efficient way in C to perform the same kind of division and modulus as in Python and Ruby?

推荐答案

与符号整数除法舍入的方向不能在较早的C类标准指定。然而,在C99它被指定为向零舍入。

The direction for rounding with signed integer division is not specified in older C standards. However, in C99 it is specified to round towards zero.

下面是便携式code与其中的C类标准的所有版本和CPU架构如下:

Here's portable code which works with all versions of the C standards and CPU architectures:

int py_div(int a, int b)
{
  if (a < 0)
    if (b < 0)
      return -a / -b;
    else
      return -(-a / b) - (-a % b != 0 ? 1 : 0);
  else if (b < 0)
      return -(a / -b) - (a % -b != 0 ? 1 : 0);
    else
      return a / b;
}

int py_mod(int a, int b)
{
  if (a < 0)
    if (b < 0)
      return -(-a % -b);
    else
      return -a % b - (-a % -b != 0 ? 1 : 0);
  else if (b < 0)
      return -(a % -b) + (-a % -b != 0 ? 1 : 0);
    else
      return a % b;
}

我做了一些肤浅的测试,它似乎给出相同的结果了Python。这code可能不是最大效率,但良好的C编译器也许可以优化它充分,特别是如果你把code在标题为静态函数。

I did some superficial tests and it appears to give the same results as Python. This code may not be maximally efficient, but a good C compiler can probably optimize it adequately, especially if you put the code in a header as static functions.

您可能也想看一看这个密切相关的问题:Integer师在C ++ 与底片舍入。

You may also want to take a look at this closely related question: Integer division rounding with negatives in C++.

这篇关于Python样式整数除法和放大器;模用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 15:39