2012-05-06 20 views

回答

17

這會給0到n之間的結果 - 1 x的正反兩方面的價值:

((x % n) + n) % n 
+0

這東西是在我的頭上,但那是有效的。謝謝! –

+1

我的朋友剛剛指出,一個較短的版本將是(n + x)%n –

+8

@TomHalladay:適用於x> = -n,但仍會給出x <-n的負面結果。 –

3

那麼,modular arithmetic是在整數的equivalence classes上完成的,所以Excel和任何RDBMS都沒有「做錯%」。如果你想在0和6之間的代表性,但是,你總是可以做

select (-3 % 7) + 7; 
+0

唯一的問題是,如果我的值是0,我需要0 –

+0

等待的結果,所以你有一對整數'M'和'N'這樣'M'是要一致0 mod'n',但是'select m%n'正在返回除零之外的東西嗎? – 2012-05-06 17:58:08

+1

@JackManey:你在'(m%n)+ n'中的答案,這給出了'(0%n)+ n = n',其中OP希望它等於'0'。這是MarkByers的答案有額外的'%n'的原因的一個子集。 – MatBailie

1

敢於沉悶(並且遲到派對)。

declare @Modulus as Int = 7 
declare @Samples as Table (Value Int) 

insert into @Samples (Value) values (-12), (-3), (0), (3), (13), (70) 

select Value, 
    case Sign(Value) 
    when 1 then Value % @Modulus 
    when -1 then Value % @Modulus + @Modulus 
    else 0 
    end as Modulus 
    from @Samples