From 7d4e79bf2589acc8bf4f6f5a60f2e0c0eaf31597 Mon Sep 17 00:00:00 2001 From: nihonium Date: Sun, 20 Feb 2022 16:32:02 +0300 Subject: [PATCH] rational.c --- numbers/rational.c | 47 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 numbers/rational.c diff --git a/numbers/rational.c b/numbers/rational.c new file mode 100644 index 0000000..75b4a05 --- /dev/null +++ b/numbers/rational.c @@ -0,0 +1,47 @@ +#include +#include +#include + +int main() { + char s[31] = ""; + int i; + double res = 0; + char irnull = 0; + char r[31], ir[31]; + scanf("%s", s); + + for (i = 0; i < 31; ++i) { + if (s[i] == '.') { + s[i] = '\0'; + break; + } + } + + ++i; + + strcpy(r, s); + + if (i < 32) { + strcpy(ir, s+i); + } + else { + irnull = 1; + } + + // Перевод целой части + int len = strlen(r); + for (i = 0; i < len; ++i) { + res += (r[i] - '0') * pow(2, len-i-1); + } + + // Если дробная часть есть, то переводим и её + if (!irnull) { + len = strlen(ir); + for (i = 1; i < len+1; ++i) { + res += (ir[i-1] - '0') * pow(2, -i); + } + } + + printf ("%.12lf", res); + return 0; +}