Advertisement
cd62131

Fraction

Jul 22nd, 2014
776
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.39 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define DIGITMAX 101 /* 100 + dummy */
  4. void recurringDecimal(int x, int y) {
  5.   int rem[DIGITMAX], quo[DIGITMAX],  r = 0, i, remainder, loop = 0;
  6.   rem[r] = 0; quo[r++] = 0; /* dummy */
  7.   printf("%d.", x / y);
  8.   while (x != 0) {
  9.     remainder = x % y;
  10.     if (!remainder) break;
  11.     for (i = 1; i < r; i++)
  12.       if (rem[i] == remainder) { loop = i; goto looped; }
  13.     rem[r] = remainder; x %= y; x *= 10; quo[r++] = x / y;
  14.     if (r > DIGITMAX) break;
  15.     continue;
  16.     looped: break;
  17.   }
  18.   if (loop) {
  19.     for (i = 1; i < r; i++) {
  20.       if (i == loop) printf("["); printf("%d", quo[i]); if (i == r - 1) printf("]");
  21.     }
  22.   } else if (r <= DIGITMAX)
  23.     for (i = 1; i < r; i++) printf("%d", quo[i]);
  24.   else {
  25.     for (i = 1; i < DIGITMAX; i++) printf("%d", quo[i]);
  26.     printf("...");
  27.   }
  28.   puts("");
  29. }
  30. int main(void) {
  31.   int x, y, i;
  32.   recurringDecimal(1, 1);
  33.   recurringDecimal(1, 3);
  34.   recurringDecimal(2, 3);
  35.   recurringDecimal(1, 8);
  36.   printf("  "); for (i = 1; i < DIGITMAX; i++) printf("%d", i % 10); puts("");
  37.   recurringDecimal(1, 991);
  38.   recurringDecimal(1, 997);
  39.   recurringDecimal(10, 89);
  40.   recurringDecimal(1234, 555);
  41.   puts("分子 分母 を正数で入力してください。");
  42.   scanf("%d%d", &x, &y);
  43.   if (x < 0) x = -x;
  44.   if (y < 0) y = -y;
  45.   printf("%d / %d = ", x, y);
  46.   recurringDecimal(x, y);
  47.   return 0;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement