当前位置:网站首页>C陷阱与缺陷 第7章 可移植性缺陷 7.7 除法运算时发生的截断
C陷阱与缺陷 第7章 可移植性缺陷 7.7 除法运算时发生的截断
2022-08-01 21:00:00 【weixin_客子光阴】
除法运算时发生的截断
q = a / b;
r = a % b;
这里,不妨假定b大于0.
我们希望a,b,q,r之间维持怎样的关系呢?
1、最重要的一点,我们希望q * b + r == a,因为这是定义余数的关系。
2、如果我们改变a的正负号,我们希望这会改变q的符号,但这不会改变q的绝对值。
3、当b>0时,我们希望保证r>=0且r<b。例如,如果余数用于哈希表的索引,确保它是一个有效的索引值很重要。
但是它们不可能同时成立。
然而,C语言的定义只保证了第1条形式,以及当a>=0且b>0时,保证|r|<|b|以及r>=0.
0 <= h < HASHSIZE, n恒为非负,那么我们只需要像下面一样简单地写:
h = n % HASHSIZE;
然而,如果n可能为负数,而此时h也有可能为负,那么这样做就不一定总是合适的了。不过,我们已知h > -HASHSIZE,
因此可以这样写:
h = n % HASHSIZE;
if (h < 0) {
h += HASHSIZE;
}
更好的做法是,程序在设计时就应该避免n的值为负这样的情形,并且声明n为无符号数。
边栏推荐
- Digital twin Beijing the imperial palace, yuan universe is the process of tourism
- 基于FPGA的任意字节数(单字节、多字节)的串口(UART)发送(含源码工程)
- Use WeChat official account to send information to designated WeChat users
- WeChat applet cloud development | personal blog applet
- 如何封装 cookie/localStorage/sessionStorage hook?
- 通过这两个 hook 回顾 Set/Map 基础知识
- [Energy Conservation Institute] Ankerui Food and Beverage Fume Monitoring Cloud Platform Helps Fight Air Pollution
- 数据库内核面试中我不会的问题(1)
- tiup mirror merge
- Telnet弱口令渗透测试
猜你喜欢

外骨骼机器人(七):标准步态数据库

扣减库存方案

30+的女性测试人面试经验分享
![[Energy Conservation Institute] Application of Intelligent Control Device in High Voltage Switchgear](/img/6d/05233ce5c91a612b6247ea07d7982e.jpg)
[Energy Conservation Institute] Application of Intelligent Control Device in High Voltage Switchgear

MySQL 中出现的字符编码错误 Incorrect string value: ‘\x\x\x\x‘ for column ‘x‘

Application of Acrel-5010 online monitoring system for key energy consumption unit energy consumption in Hunan Sanli Group

数据库内核面试中我不会的问题(1)

JS提升:手写发布订阅者模式(小白篇)

Interview assault 70: what is the glue bag and a bag?How to solve?

数据库单字段存储多个标签(位移操作)
随机推荐
基于FPGA的任意字节数(单字节、多字节)的串口(UART)发送(含源码工程)
Go Atomic
1374. 生成每种字符都是奇数个的字符串 : 简单构造模拟题
JS提升:如何中断Promise的链式调用
STAHL touch screen repair all-in-one display screen ET-316-TX-TFT common faults
记录第一次给开源项目提 PR
Little data on how to learn?Jida latest small learning data review, 26 PDF page covers the 269 - page document small data learning theory, method and application are expounded
封装一个管理 url 状态的 hook
Multithreaded producers and consumers
密码学的基础:X.690和对应的BER CER DER编码
Simple test of the use of iptables
线上问题排查常用命令,总结太全了,建议收藏!!
字符串
[Multi-task model] Progressive Layered Extraction: A Novel Multi-Task Learning Model for Personalized (RecSys'20)
Hangao data import
Protocol Buffer usage
OSG Notes: Set DO_NOT_COMPUTE_NEAR_FAR to manually calculate far and near planes
任务调度线程池基本介绍
Postman 批量测试接口详细教程
[译] 容器和 Kubernetes 中的退出码完整指南