简体   繁体   English

求解分数时如何用模计算余数?

[英]How is remainder calculated with modulo when solving fractions?

As you can see, dividing 3/7 yields a fraction. 如您所见,将3/7除以得到一个分数。 But when I do 3%7 it yields 3. How could this be? 但是当我做3%7时,它的收益为3。怎么可能呢? I suppose I expected an output value of 4 (because it would take 4 to complete 7) or 0, (because there is no remainder at all if you use integer division such as 3//7). 我想我期望输出值为4(因为要完成4到7将花费4)或0(因为如果使用整数除法(例如3 // 7)根本没有余数)。

>>> 3/7
0.42857142857142855
>>> 3%7
3
>>> 

Just trying to understand the depths of Python. 只是想了解Python的深度。 Thanks! 谢谢!

Remember long division? 还记得长期分裂吗? Before you learned about fractions, 50 divided by 7 would be 7, remainder 1 . 在您了解分数之前, 50 divided by 7将得到7, remainder 1 The remainder is the modulus. remainder为模量。 It is the numerator of the 1/7 remaining after integer division. 它是整数除后剩余的1/7的分子。

Let's use different numbers for demonstration. 让我们使用不同的数字进行演示。

42 divided by 5 gives a quotient of 8 and a remainder of 2. That means 42 // 5 == 8 and 42 % 5 == 2 . 42除以5得到的商为8,余数为2。这意味着42 // 5 == 842 % 5 == 2

3 divided by 7 gives a quotient of 0 and a remainder of 3. That means 3 // 7 == 0 and 3 % 7 == 3 . 3除以7得到的商为0,余数为3。这意味着3 // 7 == 03 % 7 == 3

In Python, // and % represent the quotient and remainder you probably learned about before you learned about fractions and real numbers. 在Python中, //%表示在学习分数和实数之前您可能已经了解的商和余数。 The only (possible) difference is that // floors and % matches the sign of the right-hand operand. 唯一(可能)的区别是, // floor和%匹配右侧操作数的符号。

modulo returns the whole number after integer (floor) division. 模返回整数(底数)后的整数。

>>>3//7
0 # with remainder 3
>>>3%7
3
>>>2//5
2 # with remainder 1
>>>2%5
1

Re-reading your question, it occurred to me you got your terms mixed up and that may have been the underlying confusion that none of us properly answered. 重新阅读您的问题,对我来说,您感到困惑,这可能是我们根本无法正确回答的潜在混乱。

But when I do 3%7 it yields 3. How could this be? 但是当我做3%7时,它的收益为3。怎么可能呢? I suppose I expected an output value of 4 (because it would take 4 to complete 7) 我想我期望的输出值为4(因为完成4需要花费4)

So first that issue was masked when you said 4. Since 4 is greater than 3, 3 can be subtracted a second time, leaving 1. So 1 is the output of 7 % 3 . 因此,首先,当您说4时,该问题被掩盖了。由于4大于3,因此可以第二次减去3,留下1。因此17 % 3的输出。

But you asked about 3 % 7 , even though you then proceeded to explain 7 % 3 . 但是您询问了3 % 7 ,即使您随后继续解释了7 % 3 3 % 7 is less than 1 (because 7 > 3). 3 % 7小于1(因为7> 3)。 So that is why the modulus is still 3. Integer division gives you 0, so 3 is left. 就是为什么模数仍为3的原因。整数除法为0,所以剩下3。

Take the first term (3) divided by the second term (7) using integer division (resulting in 0). 用整数除法将第一项(3)除以第二项(7)(结果为0)。 Subtract that number from the first term (3) and you get 3. So: 3 % 7 = 3 从第一个项(3)中减去该数字,您得到3。因此: 3 % 7 = 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM