fork download
  1. /*
  2.   出されたお題をコーディングして罵られるスレ
  3.   http://t...content-available-to-author-only...h.net/test/read.cgi/tech/1354393458/18
  4.   実数 x の n 乗根を求めよ。
  5.   ただし、
  6.   ・math.hを使わない
  7.   ・double x > 1.0 の任意
  8.   ・int n > 1 の任意
  9. */
  10. #include<stdio.h>
  11. #include<stdlib.h>
  12. //#include<float.h>
  13.  
  14. int main()
  15. {
  16. char buff[256];
  17. double x;
  18. int n;
  19. int i;
  20. double xmin, xmax, tmp, seki;
  21.  
  22. while (1) {
  23. // 入力
  24. printf("\n入力 (範囲外の数値を入力するか、Ctrl+C で終了)\n");
  25. printf(" x (>1.0) = ");
  26. fgets(buff, sizeof(buff), stdin);
  27. x = atof(buff);
  28. if (x <= 1.0) {
  29. printf("exit\n");
  30. return 1;
  31. }
  32. printf(" n (>1 ) = ");
  33. fgets(buff, sizeof(buff), stdin);
  34. n = atoi(buff);
  35. if (n <= 1) {
  36. printf("exit\n");
  37. return 2;
  38. }
  39. // xmax, xmin の中間値 tmp を実際にn乗した結果を目的の x と比較して、
  40. // 違えば xmax, xmin の値を狭めていく
  41. xmin = 1.0;
  42. xmax = x;
  43. while (1) {
  44. // 中間値
  45. tmp = (xmin + xmax) / 2;
  46. // tmp が xmax, xmin どちらかにくっついてしまったら、これまで
  47. if (tmp == xmin || tmp == xmax) {
  48. break;
  49. }
  50. // 実際にn乗
  51. seki = 1.0;
  52. for (i = 0; i < n; i++) {
  53. seki *= tmp;
  54. }
  55. // 判定して狭める
  56. if (seki < x) {
  57. xmin = tmp;
  58. } else if (seki > x) {
  59. xmax = tmp;
  60. } else {
  61. break; // ジャスト
  62. }
  63. }
  64. // 結果表示
  65. printf("result = %.10f\n", tmp);
  66. // 確認
  67. seki = tmp;
  68. for (i = 1; i < n; i++) {
  69. seki *= tmp;
  70. }
  71. printf("(check = %.10f)\n", seki);
  72. }
  73.  
  74. return 0;
  75. }
  76.  
  77. //DBL_EPSILON
Runtime error #stdin #stdout 0.02s 1724KB
stdin
8
6
0
stdout
入力 (範囲外の数値を入力するか、Ctrl+C で終了)
 x (>1.0) =  n (>1  ) = result = 1.4142135624
(check = 8.0000000000)

入力 (範囲外の数値を入力するか、Ctrl+C で終了)
 x (>1.0) = exit