| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1799 人关注过本帖
标题:新手问题关于模?例如(-8)%(3)?
只看楼主 加入收藏
peach5460
Rank: 15Rank: 15Rank: 15Rank: 15Rank: 15
来 自:武汉
等 级:贵宾
威 望:30
帖 子:2780
专家分:6060
注 册:2008-1-28
收藏
得分:0 
简单说...
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的编译器,我到没见过"

我总觉得授人以鱼不如授人以渔...
可是总有些SB叫嚣着:要么给代码给答案,要么滚蛋...
虽然我知道不要跟SB一般见识,但是我真的没修炼到宠辱不惊...
2008-02-20 23:24
leeco
Rank: 4
等 级:贵宾
威 望:10
帖 子:1029
专家分:177
注 册:2007-5-10
收藏
得分:0 
回复 11# 的帖子
你没有触动我……,我只是没见过,让你举一个看看……
2008-02-21 09:49
leeco
Rank: 4
等 级:贵宾
威 望:10
帖 子:1029
专家分:177
注 册:2007-5-10
收藏
得分:0 
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取整,如果有少数编译器不是这样做的,那么说明它们不符合标准。
2008-02-21 10:40
默默无纹
Rank: 1
等 级:新手上路
帖 子:45
专家分:0
注 册:2008-2-12
收藏
得分:0 
强烈感谢大家,谢谢各位的不吝指教,和谐社会,和谐大家。
2008-02-21 20:18
peach5460
Rank: 15Rank: 15Rank: 15Rank: 15Rank: 15
来 自:武汉
等 级:贵宾
威 望:30
帖 子:2780
专家分:6060
注 册:2008-1-28
收藏
得分:0 
额...那我可能说错了...原来取整是有标准的啊...
不过是不是编译器是否完全符合标准还不一定哈...

比如VC6.0就有一些地方编译结果和标准不同...

所以提醒楼主编程的时候要避开这些模棱两可的表达式啊

我总觉得授人以鱼不如授人以渔...
可是总有些SB叫嚣着:要么给代码给答案,要么滚蛋...
虽然我知道不要跟SB一般见识,但是我真的没修炼到宠辱不惊...
2008-02-22 09:09
快速回复:新手问题关于模?例如(-8)%(3)?
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.017319 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved