LoginSignup
2
0

More than 5 years have passed since last update.

C++とRubyの割り算は違う

Last updated at Posted at 2018-09-10

C++のテストデータをRubyで作っていたら1時間ぐらいハマったのでメモ

マイナスの値の割り算結果がC++とRubyでは違う。

divmod.cpp
#include <iostream>

int main(void)
{
    std::cout << "10 / 3 = " << 10 / 3 << ", 10 % 3 = " << 10 % 3 << std::endl;
    std::cout << "-10 / 3 = " << -10 / 3 << ", -10 % 3 = " << -10 % 3 << std::endl;
    std::cout << "10 / -3 = " << 10 / -3 << ", 10 % -3 = " << 10 % -3 << std::endl;
    std::cout << "-10 / -3 = " << -10 / -3 << ", -10 % -3 = " << -10 % -3 << std::endl;
    std::cout << "11 / 3 = " << 11 / 3 << ", 11 % 3 = " << 11 % 3 << std::endl;
    std::cout << "-11 / 3 = " << -11 / 3 << ", -11 % 3 = " << -11 % 3 << std::endl;
    std::cout << "11 / -3 = " << 11 / -3 << ", 11 % -3 = " << 11 % -3 << std::endl;
    std::cout << "-11 / -3 = " << -11 / -3 << ", -11 % -3 = " << -11 % -3 << std::endl;
    return 0;
}

実行結果

10 / 3 = 3, 10 % 3 = 1
-10 / 3 = -3, -10 % 3 = -1
10 / -3 = -3, 10 % -3 = 1
-10 / -3 = 3, -10 % -3 = -1
11 / 3 = 3, 11 % 3 = 2
-11 / 3 = -3, -11 % 3 = -2
11 / -3 = -3, 11 % -3 = 2
-11 / -3 = 3, -11 % -3 = -2
divmod.rb
puts '10 / 3 = %d, 10 %% 3 = %d' % [ 10 / 3, 10 % 3, ]
puts '-10 / 3 = %d, -10 %% 3 = %d' % [ -10 / 3, -10 % 3, ]
puts '10 / -3 = %d, 10 %% -3 = %d' % [ 10 / -3, 10 % -3, ]
puts '-10 / -3 = %d, -10 %% -3 = %d' % [ -10 / -3, -10 % -3, ]
puts '11 / 3 = %d, 11 %% 3 = %d' % [ 11 / 3, 11 % 3, ]
puts '-11 / 3 = %d, -11 %% 3 = %d' % [ -11 / 3, -11 % 3, ]
puts '11 / -3 = %d, 11 %% -3 = %d' % [ 11 / -3, 11 % -3, ]
puts '-11 / -3 = %d, -11 %% -3 = %d' % [ -11 / -3, -11 % -3, ]

実行結果

10 / 3 = 3, 10 % 3 = 1
-10 / 3 = -4, -10 % 3 = 2
10 / -3 = -4, 10 % -3 = -2
-10 / -3 = 3, -10 % -3 = -1
11 / 3 = 3, 11 % 3 = 2
-11 / 3 = -4, -11 % 3 = 1
11 / -3 = -4, 11 % -3 = -1
-11 / -3 = 3, -11 % -3 = -2

C++は結果がマイナスになる割り算は0に近づくのに対して、
Rubyは反対方向に丸められる。

どちらも

a / b * b + (a % b) == a

はtrue。

(-a / b) * -1 == a / b

はRubyで割り算の結果が割り切れないときはfalse。
C++とRubyで割り算の結果が割り切れるときはtrue。

この違いが何によるものなのかは少し調べた限りでは分からなかった…

2
0
1

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
2
0