21/-5在数学上等于-4.2...
21/5在数学上等于4.2
C语言规定...除号两边是int类型的时候,结果也要是int...所以必须截断小数部分...
但是C语言没有规定是如何截断...
如果按照向大一的整数取整...
21/-5=-4
21/5=5(此时21%5=-4的)
如果按小一的整数取整...
21/-5=-5(此时21%-5=4的)
21/5=4
在这里,大多数编译器采用的是向0取整...所以
21/-5=-4
21/5=4
我这里说楼主问的问题是没有答案的原因就在于此...
虽然多数编译器是向0取整的...但是你无可预料客户的编译器是什么...(这也是软件测试的一个环节...兼容性测试)
所以编代码的时候必须注意编译器不同所造成的结果差异...
楼主还是个新手...你这么告诉他21%-5一定是1,我觉得是害他...
对于这个问题...我觉得我说到这里就行了...我不知道我什么地方触动了你...你会怒气冲冲的回帖"你列举一个商是-3的编译器,我到没见过"
----------------解决方案--------------------------------------------------------
回复 11# 的帖子
你没有触动我……,我只是没见过,让你举一个看看…… ----------------解决方案--------------------------------------------------------
Syntax
1 multiplicative-expression:
cast-expression
multiplicative-expression * cast-expression
multiplicative-expression / cast-expression
multiplicative-expression % cast-expression
Constraints
2 Each of the operands shall have arithmetic type. The operands of the % operator shall
have integer type.
Semantics
3 The usual arithmetic conversions are performed on the operands.
4 The result of the binary * operator is the product of the operands.
5 The result of the / operator is the quotient from the division of the first operand by the
second; the result of the % operator is the remainder. In both operations, if the value of
the second operand is zero, the behavior is undefined.
6 When integers are divided, the result of the / operator is the algebraic quotient with any
fractional part discarded.87) If the quotient a/b is representable, the expression
(a/b)*b + a%b shall equal a.
87) This is often called 'truncation toward zero'.
引自:ISO/IEC 9899:1999 (E) Page 82
引文中在描述%运算符时用到 "the algebraic quotient with any fractional part discarded","This is often called 'truncation toward zero' ",我想正是你所说的向0取整,如果有少数编译器不是这样做的,那么说明它们不符合标准。
----------------解决方案--------------------------------------------------------
强烈感谢大家,谢谢各位的不吝指教,和谐社会,和谐大家。
----------------解决方案--------------------------------------------------------
额...那我可能说错了...原来取整是有标准的啊...
不过是不是编译器是否完全符合标准还不一定哈...
比如VC6.0就有一些地方编译结果和标准不同...
所以提醒楼主编程的时候要避开这些模棱两可的表达式啊
----------------解决方案--------------------------------------------------------