jackie wrote:
I know in c that 3/2 gets 1 and 3%2 is also 1,and i think this is
guaranteed by C99(is that true?),but on the other hand,-3/2 may be -1
or -2,and -3%2 may be -1 and 1 respectively,it is implement-
dependent,so,is my understanding of this true(positive division and
mod is guaranteed while negative is not)? thx for your help in
advance..
What you say was true for only in C90; in C99 section 6.5.5p6 says "When
integers are divided, the result of the / operator is the algebraic
quotient with any fractional part discarded.90)". The "90)" refers to
footnote 90, which says: 'This is often called ‘‘truncation toward zero"'.
What that means is that if the algebraic quotient is -1.5, the result -1
(the .5 is discarded). Since 1.5 gets rounded to 1, and -1.5 gets
rounded to -1, both rounded results are closer to 0 than the un-rounded
results, which is why this is referred to as "toward zero".
This causes problems for me. When I use negative numbers in such
calculations, what I want, far more often than not, is what they call
"rounding to negative infinity" - 1.5 gets rounded to 1, and -1.5 gets
rounded to -2 - both results are closer to negative infinity than the
number before rounding. However, standardizing it to round toward zero
still makes things a lot easier for me than not standardizing it at all.