题解 | #将真分数分解为埃及分数#
将真分数分解为埃及分数
https://www.nowcoder.com/practice/e0480b2c6aa24bfba0935ffcca3ccb7b
//只说输出成埃及分数,没说一定得不一样 #include <stdio.h> #include <string.h> #include <math.h> int main() { int a, b; char str[10]; while (scanf("%s", str) != EOF ) { int len = strlen(str); int fs[2] = {0}; int x = 0, z = 0; for (int i = len-1; i >= 0; i--) { if (str[i] == '/') { x++; z = 0; continue; } fs[x] = (str[i] - '0')* pow(10, z++) + fs[x]; // printf("%d\n",fs[0]); // printf("%d\n",fs[1]); } //printf("%d/%d\n",fs[0],fs[1]); for (int i = 0; i < fs[1] - 1; i++) { printf("1/%d+", fs[0]); } printf("1/%d\n", fs[0]); } } /*运算超时 #include <math.h> #include <stdio.h> #include <string.h> int t = 2; float y = 0.5; void aj(float a) { if ((a - y) > 0) { a = a - y; //printf("%f\n",y); printf("1/%d+", t); t++; y = pow(t, -1); aj(a); } else if ((a - y) < 0) { t++; y = pow(t, -1); aj(a); } else if ((a - y) == 0) { printf("1/%d\n", t); t = 2; y = 0.5; return; } } int main() { char str[10]; while (scanf("%s", str) != EOF ) { int len = strlen(str); float fs[2] = {0}; int x = 0, z = 0; for (int i = 0; i < len; i++) { if (str[i] == '/') { x++; z = 0; continue; } fs[x] = (str[i] - '0') + fs[x] * pow(10, z++); // printf("%d\n",fs[0]); // printf("%d\n",fs[1]); } //printf("%d/%d\n",fs[0],fs[1]); float num = fs[0] / fs[1]; aj(num); } return 0; }**/