这个问题挺有意思的,^_^
#include <stdio.h>
#include <string.h>
#include <math.h>
typedef struct {
int a, b;
} ratio_t;
ratio_t get_ratio(double num) {
char buf[1024];
snprintf(buf, 1024, "%lf", num);
int len = strlen(buf);
for(int i = len - 1; i >= 0; --i) {
if(buf[i] != '0') {
buf[i + 1] = '\0';
len = i + 1;
break;
}
}
char *p = strchr(buf, '.');
int n = buf + len - (p + 1);
ratio_t ret;
ret.a = num * pow(10, n);
ret.b = pow(10, n);
return ret;
}
int main(void) {
ratio_t ratio = get_ratio(8.52);
printf("8.52 -> %d,%d\n", ratio.a, ratio.b);
ratio = get_ratio(8);
printf("8 -> %d,%d\n", ratio.a, ratio.b);
return 0;
}
|