Please explain why 17 % 40 = 17

青春壹個敷衍的年華 提交于 2019-12-20 05:40:14

问题


I am new to Java, actually programming in general. I understand that the modulus operator (%) returns the remainder of two numbers, however, I do not understand why 17 % 40 = 17.

I understand that 40 % 17 = 6, and 17 % 5 = 2, and 40 % 5 = 0. I get the gist of what value is returned as the remainder. But 17 % 40 = 17 has me stumped.

The only rationalization I can devise is that since the remainder is less than 1 the total value 17 is returned, why not 0? Please help to explain this enigma to me.


回答1:


When you divide 17/40, quotient is 0 and the remainder is 17.

The modulo operator (%) returns the remainder.

i.e

a % b = remainder of a / b



回答2:


Java has one important arithmetical operator you may not be familiar with, %, also known as the modulus or remainder operator. The % operator returns the remainder of two numbers. For instance 10 % 3 is 1 because 10 divided by 3 leaves a remainder of 1.

So in your case 17/40 will leave remainder 17 so result is 17.

Its same as Like.

1%10 = 1



回答3:


Equation from Wiki by Knuth:

a = 17
n = 40
floor(a/n) = 0
so r = 17

When n > a then r is simply a.




回答4:


i guess learning back the 3rd and 4th standard maths is the key point.

if u see (hope understand the division syntax. its the popular 3rd std way )

  ____
40)17

you will get a reminder 17 as 17 is not divisible by 40. then there will be an adition of '.' and then the fraction will be added




回答5:


If you have the numbers a and b, their quotient q and remainder r, then the following has to be true:

q · b + r = a

That is, if you multiply the quotient (q) by the divisor (b) and add the remainder (r), the result is the dividend (a).

In your case a = 17, b = 40, q = 0 and so r has to be 17.

Note: the equation above is just a rearrangement of the equation from Nikolay Kuznetsov's answer, but I think it's easier to understand this way.




回答6:


Maybe this is a different and more helpful way to think about it.

When we apply division to integer numbers a and b, we are really trying to relate a and b like this:

a = Q * b + R

a is some multiple of b, plus some leftover. Q and R are integers; to keep this simple, let's also just think of non-negative numbers. The multiple, Q, is the quotient and leftover, R, is the remainder -- the smallest ones that make this relation work.

In most languages, a / b gives you Q, and and a % b gives you R. (In fact processors tend to compute both at once -- these are so related.)

So if a is 17 and b is 40, it only works if you write:

17 = 0 * 40 + 17

This is why a % b must be 17.

(Note that it gets more complex when considering negative numbers.)



来源:https://stackoverflow.com/questions/14473190/please-explain-why-17-40-17

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!