ゼロ除算

「==」はバグの元と広く知られていたので今まで「<」を使ってゼロ除算を監視していたのだが、どうも動作が怪しいようだ。
と、言う訳で調べてみたら、驚愕(?)の結果が。

#include <stdio.h>
#include <stdlib.h>

int main ( int argc, char* argv[])
{
  if( argc != 4){
    printf( "usage : exe [top] [bottom] [loop]\n");
    return -1;
  }
  double top = atof( argv[1]);
  double bot = atof( argv[2]);
  int loop = atoi( argv[3]);

  for( int i = 0; i < loop; i++){
    double r = top / bot;
    printf( "%d,%le\n", i, r);

    if( bot < 0.0){
      printf( "bot < zero detect,%d\n", i);
      break;
    }

    if( bot != 0.0){
    } else {
      printf( "bot = zero detect,%d\n", i);
      break;
    }
    bot /= 10.0;
  }

  return 0;
}

実行結果(gcc 4.1.2)

$ a.out 1.0 1.0 1000
308,1.000000e+308
309,inf
310,inf
311,inf
312,inf
313,inf
314,inf
315,inf
316,inf
317,inf
318,inf
319,inf
320,inf
321,inf
322,inf
323,inf
324,inf
bot = zero detect,324
$ a.out 0.0 1.0 1000
323,0.000000e+00
324,nan
bot = zero detect,324

分母のみでなく、計算結果もチェックしないとダメのご様子。
固定観念はアカンと思い知りました。
ノムさんの本であれほど書かれていたのに・・・。