Skip to content

Instantly share code, notes, and snippets.

@maehrm
Created March 24, 2019 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maehrm/7aca47c68b1eca95ae2a347d04cd623d to your computer and use it in GitHub Desktop.
Save maehrm/7aca47c68b1eca95ae2a347d04cd623d to your computer and use it in GitHub Desktop.
平成20年度春期試験_基本情報午後問10
#include <stdio.h>
#include <ctype.h>
void tofraction(char *);
long power10(int);
long gcd(long, long);
void tofraction(char *str) {
long numerator = 0; /* 分子 */
long denominator; /* 分母 */
int flag = 0;
int n = 0; /* 準関節を除く小数部のけた数 */
int k = 0; /* 準関節のけた数 */
long measure; /* 分子と分母の最大公約数 */
while (*str != '\0') {
if (isdigit(*str)) { /* 10進数字か? */
numerator *= 10;
numerator += *str - '0';
if (flag == 1) n++;
if (flag == 2) k++;
} else if (*str == '.') {
flag = 1;
} else if (*str == '{') {
flag = 2;
}
str++;
}
if (flag != 2) { /* 有限小数又は整数の場合 */
denominator = power10(n);
} else {
denominator = power10(n) * (power10(k) - 1);
numerator -= numerator / power10(k);
}
measure = gcd(numerator, denominator);
numerator /= measure;
denominator /= measure;
printf("= %ld/%ld\n", numerator, denominator);
}
long power10(int num) {
long ret = 10;
int i;
if (num == 0) return 1;
for (i = 1; i < num; i++) {
ret *= 10;
}
return ret;
}
long gcd(long a, long b) {
long tmp, r;
if (a < b) {
tmp = a;
a = b;
b = tmp;
}
r = a % b;
while (r != 0) {
a = b;
b = r;
r = a % b;
}
return b;
}
int main(void) {
char *example[] = { "32",
"5.237",
"0.875",
"1.{3}",
"0.2{142857}" };
int i, size = sizeof(example) / sizeof(example[0]);
for (i = 0; i < size; i++) {
printf("%s ", example[i]);
tofraction(example[i]);
}
return 0;
}
@maehrm
Copy link
Author

maehrm commented Mar 24, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment