简体   繁体   English

C整数除法和楼层

[英]C integer division and floor

In C, is there a difference between integer division a/b and floor(a/b) where both a and b are integers? 在C中,整数除法a / b与floor(a / b)之间是否存在差异,其中a和b都是整数? More specifically what happens during both processes? 更具体地说,在两个过程中发生了什

a/b does integer division. a/b整数除法。 If either a or b is negative, the result depends on the compiler (rounding can go toward zero or toward negative infinity in pre-C99; in C99+, the rounding goes toward 0). 如果ab为负数,则结果取决于编译器(在C99之前,舍入可以趋向零或朝向负无穷大;在C99 +中,舍入趋向于0)。 The result has type int . 结果是int类型。 floor(a/b) does the same division, converts the result to double, discards the (nonexistent) fractional part, and returns the result as a double. floor(a/b)执行相同的除法,将结果转换为double,丢弃(不存在的)小数部分,并将结果作为double返回。

floor returns a double while a / b where both a and b are integers yields an integer value. floor返回一个doublea / b ,其中ab都是整数,产生一个整数值。

With the correct cast the value is the same. 使用正确的强制转换,值是相同的。

If typeof operator existed in C (it does not) we would have: 如果typeof运算符存在于C(它没有),我们会:

(typeof (a /b)) floor(a / b) == a / b

EDIT: Now if the question is: is there any difference between: 编辑:现在,如果问题是:是否有任何区别:

(double) (a / b)

and

floor(a / (double) b)

the answer is yes. 答案是肯定的。 The results differ with respect to negative values. 结果与负值不同。

It's possible to lose information converting from integer to floating point. 丢失从整数转换为浮点的信息是可能的。 Not likely with int and double, but with slight alteration: int和double不太可能,但稍有改动:

#include <stdio.h>
#include <math.h>

int main(void)
{
    unsigned long long a = 9000000000000000003;
    unsigned long long b = 3;
    printf("a/b = %llu\n", a/b);
    printf("floor(a/b) = %f\n", floor(a/b));
    return 0;
}

Result: 结果:

a/b = 3000000000000000001
floor(a/b) = 3000000000000000000.000000

In general, assuming that the integers are representable in both the integer and the floating-point types, there isn't a difference, but the proof is not obvious. 一般来说,假设整数和浮点类型都可以表示整数,没有区别,但证明并不明显。 The problem is that in floating-point, a rounding occurs in the division a/b, so that the floor function doesn't apply on the exact rational value, but on an approximate value. 问题是在浮点数中,在分区a / b中发生舍入,因此floor函数不适用于精确的有理值,而是应用于近似值。 I had written a paper on the subject: https://www.vinc17.net/research/publi.html#Lef2005b 我写了一篇关于这个主题的论文: https//www.vinc17.net/research/publi.html#Lef2005b

In short, the result I've obtained is that if a - b is exactly representable in the floating-point system, then floor(a/b), where a and b are floating-point numbers (with integer values), gives the same result as the integer division a/b. 简而言之,我得到的结果是,如果a-b在浮点系统中是完全可表示的,那么floor(a / b),其中a和b是浮点数(带整数值),给出与整数除法a / b相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM