LoginSignup
1
0

More than 5 years have passed since last update.

C | Python > マイナス値のmodulo(%)演算 > C:マイナスを返す | Python:プラスを返す

Last updated at Posted at 2018-02-13

Pythonで一定時間ごとに処理を実行する
の実装で以下のmodulo(%)演算はマイナス値が返ると思っていた自分がいました。

next_time = ((base_time - time.time()) % interval) or interval

C

#include <stdio.h>

int main(void) {
    int val = -3;
    printf("%d\n", val % 5);
    return 0;
}
run
-3

Python 3.5

val=-3
print(val % 5)
run
2

備考

Pythonをよく使う人は知っていることなのかもしれない。

https://docs.python.org/3/reference/expressions.html
下記の赤文字は強調のため色付けした。

The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand

1
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0