From Test-Scratch-Wiki

() 除 () 的馀数
() 除 () 的餘數
类别 运算类积木
形狀 椭圆形积木

The () Mod () 积木 ("mod" is short for "modulo") is an 运算类积木 and a 椭圆形积木. The block reports the remainder of the division when the first value is divided by the second. For example, when 10 is put in the first input and 3 in the second, the block will report 1; 10 divided by 3 gives a remainder of 1.

Negative numbers behave a little differently, because a remainder must always be positive. -10 mod 3 equals 2, not -1, because you have to multiply 3 by -4 to have any remainder at all.

用法示例

If a 专案 is doing divisibility tests, the () Mod () block can be of use.

Some common uses for the () Mod () block:

  • Checking if two numbers divide without a remainder
如果 <((a) 除 (b) 的餘數) = [0]> 那麼 
  說出 [a is divisible by b]
否則
  說出 [a is not divisible by b]
end
  • Checking if a number is a whole number
如果 <((a) 除 (1) 的餘數) = [0]> 那麼 
  說出 [a is a whole number]
否則
  說出 [a is not a whole number]
end
  • Checking if numbers are odd or even
如果 <((a) 除 (2) 的餘數) = [0]> 那麼 
  說出 [a is an even number]

  如果 <((a) 除 (1) 的餘數) = [0]> 那麼 
    說出 [a is an odd number]
  否則
    說出 [a is not an integer]
  end
end
  • Repeatedly iterating through a 清单:
當 @greenflag 被點擊
變數 [x v] 設為 [0]
重複無限次 
  變數 [x v] 改變 (1)
  說出 (清單第 (x 座標) 項項目\( [list v] \) :: list)
  變數 [x v] 設為 ((x 座標) 除 (清單 [list v] 的項目數 :: list) 的餘數)
end
  • Reusing background-sprites when scrolling
當 @greenflag 被點擊
重複無限次 
  x 設為 (((x座標) + (240)) 除 (480) 的餘數)
end

应用

Main article: List of Block Workarounds

If only positive numbers are wanted, the block can be replicated with the following code (the 变量 remainder is the reported value):

如果 <(四捨五入數值 ((a) / (b))) > ((a) / (b))> 那麼 
  變數 [remainder v] 設為 ((a) - ((四捨五入數值 (((a) / (b)) - (0.5))) * (b)))

  變數 [remainder v] 設為 ((a) - ((四捨五入數值 ((a) / (b))) * (b)))
end

Negative values are rarely used in the () Mod () block, although it is possible. The output given when a negative value is in the first insert and a positive value is in the second is the positive value, so if the negative value is wanted, you must subtract the number in the second insert from the remainder, as so:

如果 <(a) < (0)> 那麼 
  如果 <(b) > (0)> 那麼 
    變數 [remainder v] 設為 (((a) 除 (b) 的餘數) - (b))
  
    變數 [remainder v] 設為 ((a) 除 (b) 的餘數)
  end

  變數 [remainder v] 設為 ((a) 除 (b) 的餘數)
end

参见

Cookies help us deliver our services. By using our services, you agree to our use of cookies.