fork download
  1. #include <stdio.h>
  2. #include <math.h>
  3. void metric_prefix(int x, double *d, const char **p) {
  4. static const char *prefixes[] = {"", "k", "M", "G"};
  5. int y = 1000, e = floor(log(x) / log(y));
  6. *d = x / pow(y, e);
  7. *p = prefixes[e];
  8. }
  9. void binary_prefix(int x, double *d, const char **p) {
  10. static const char *prefixes[] = {"", "Ki", "Mi", "Gi"};
  11. int y = 1024, e = floor(log(x) / log(y));
  12. *d = x / pow(y, e);
  13. *p = prefixes[e];
  14. }
  15. int main() {
  16. double d;
  17. const char *p;
  18. #define f(x) metric_prefix(x, &d, &p), printf("%d: %g %s\n", x, d, p)
  19. f(999), f(1000), f(10001);
  20. f(1000000), f(1000000000);
  21. #define g(x) binary_prefix(x, &d, &p), printf("%d: %g %s\n", x, d, p)
  22. g(1023), g(1024), g(1025);
  23. g(1048576), g(1073741824);
  24. return 0;
  25. }
  26.  
Success #stdin #stdout 0s 9424KB
stdin
Standard input is empty
stdout
999: 999 
1000: 1 k
10001: 10.001 k
1000000: 1 M
1000000000: 1 G
1023: 1023 
1024: 1 Ki
1025: 1.00098 Ki
1048576: 1 Mi
1073741824: 1 Gi