对负数取模

编程入门 行业动态 更新时间:2024-10-26 14:40:31
本文介绍了对负数取模的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

模运算a%b返回a/b的余数,但对于负数则不这样做.

A modulo operation a%b returns the remainder for a/b but for negative numbers it does not do so.

#include <stdio.h> int main(void) { int n=-4; printf("%d\n",n%3); return 0; }

它应该返回2,因为3 *(-2)=-6小于-4且是3的倍数,但输出为-1. 为什么将(-a) mod b与-(a mod b)

It should return 2 as 3*(-2)=-6 is just smaller than -4 and a multiple of 3 but the output is -1. Why is it treating (-a) mod b same as -(a mod b)

推荐答案

作为一般规则,模和除法应满足方程式

As a general rule, the modulo and division should satisfy the equation

b * (a/b) + a%b == a

对于正数,很明显,这意味着a%b必须为正数.但是,如果a/b为负,则结果将四舍五入为零.

For positive numbers, it is obvious that this means that a%b must be a positive number. But if a/b is negative, then the result is rounded towards zero.

因此,以 a = -4, b = 3为例.我们知道 a / b = -1.3333,四舍五入为a/b == -1.从上面的方程式中,我们可以得到b * (-1) + a%b == a.如果我们插入a和b,则会得到-3 + a%b == -4,并且看到a%b必须为-1.

So take for instance a = -4, b = 3. We know that a/b = -1.3333, which rounded towards zero becomes a/b == -1. From the equation above, we have that b * (-1) + a%b == a. If we insert a and b, we get -3 + a%b == -4, and we see that a%b must be -1.

更多推荐

对负数取模

本文发布于:2023-10-24 08:57:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1523505.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:负数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!