余数运算符的等效操作,用于处理低于允许的最小值
Equivalent operation to remainder operator for handling values below the minimal allowed
我在从0到5的循环中有一组索引。如果用户指定的索引大于 5,例如 7,则应返回索引 7-6=1。如果指定的索引低于 0,例如 -2,则应返回索引 -2+6=4。
在第一种情况下,我们可以使用余数运算符来处理上面的值 5:
int inputValue = 7;
int result = inputValue%6;
但是,是否有类似的操作来优雅地处理指定的索引低于 0 的情况?一个黑客的解决方案是:
if (inputValue < 0)
result = inputValue+6;
else
result = inputValue;
这仅处理大于或等于 -6 的值
如果你将负数修改为 6,你会得到一个负数,但你可以只加 6 得到你的正余数:
int result = (inputValue % 6) + (inputValue < 0? 6 : 0);
或者,使用将 6 加到正余数的事实会留下具有相同余数的数字:
int result = ((inputValue % 6) + 6) % 6;
希望这有帮助!
相关文章:
- 余数运算符的等效操作,用于处理低于允许的最小值
- 该程序允许用户处理循环,只要用户输入奇数
- 预处理的 C/C++ 文件是否特定于计算机?
- 如果 LTO 中的代码依赖于其构造的副作用,是否允许 LTO 删除未使用的全局对象?
- C 中的Arduino类是否类似于处理中的最小类
- boost::asio 允许非阻塞接受新连接,而连接的处理程序正在阻塞
- 编写一个通用遍历函数,允许灵活地处理具有不同参数的多个函数
- 拘泥于处理(数学)集合和子集的练习
- 如何处理"警告:在参数声明中使用'auto'仅适用于 -fconcepts"
- 如何防止基于 MFC 对话框的应用在 ESC 键后关闭,但允许其他控件处理它
- 允许子面板处理鼠标运动事件
- 在Qt中如何处理相对于光标位置的光标形状
- 如何更好地处理依赖于模板参数的类成员类型
- 如何在R中处理C++内部数据结构以允许保存/加载
- 如何允许setw应用于以下所有stdout
- 在将 dijkstra 的算法应用于此时,我究竟如何处理以下情况?
- 如何卸载高度依赖于正确异常处理的计算繁重的任务
- 如何欺骗boost::asio来允许只移动的处理程序
- 在信号处理程序中不允许对象或函数
- 为什么标准不允许在模板形参列表中初始化依赖于常量的类型