fork(5) download
  1. /*
  2. 平方根を自前で求めるプログラム
  3. */
  4.  
  5. #include <stdio.h>
  6.  
  7. // 平方根の誤差。小さいほど正確な平方根が求められる
  8. #define SQRT_F 0.0000001
  9.  
  10. double myabs(double n){ return (n<0.0) ? -n : n ; }
  11. // nの平方根を求める関数
  12. double mysqrt( double n ){
  13. double ret=0.0, pre=0.0, plus=1.0;
  14.  
  15. do{
  16. pre=ret;
  17. ret+=plus;
  18. if( ret*ret > n ){ // 飛び越したら値を戻し、加算値を減らす
  19. ret=pre;
  20. plus*=0.1;
  21. }
  22. } while( myabs(n-ret*ret) > SQRT_F );
  23.  
  24. return ret;
  25. }
  26.  
  27. #define FUNC(_PARAM_) printf("%lfの平方根は%lfです。\n", _PARAM_, mysqrt(_PARAM_) )
  28.  
  29. int main(void) {
  30. FUNC(1.0);
  31. FUNC(2.0);
  32. FUNC(3.0);
  33. FUNC(4.0);
  34. FUNC(5.0);
  35. FUNC(6.0);
  36. FUNC(7.0);
  37. FUNC(8.0);
  38. FUNC(9.0);
  39. FUNC(16.0);
  40.  
  41. return 0;
  42. }
  43.  
Success #stdin #stdout 0s 5496KB
stdin
Standard input is empty
stdout
1.000000の平方根は1.000000です。
2.000000の平方根は1.414214です。
3.000000の平方根は1.732051です。
4.000000の平方根は2.000000です。
5.000000の平方根は2.236068です。
6.000000の平方根は2.449490です。
7.000000の平方根は2.645751です。
8.000000の平方根は2.828427です。
9.000000の平方根は3.000000です。
16.000000の平方根は4.000000です。