fork(2) download
  1. #include <iostream>
  2. #include <sstream>
  3. #include <utility>
  4. #include <string>
  5. #include <cmath>
  6. #include <limits>
  7.  
  8. typedef std::pair<int, int> Fraction;
  9.  
  10. int gcd(int a, int b) {
  11. int c;
  12. while (a != 0) {
  13. c = a;
  14. a = b % a;
  15. b = c;
  16. }
  17. return b;
  18. }
  19.  
  20. int wholeDigits(double x) {
  21. if (x < 1)
  22. return 0;
  23. return (int)log10(x) + 1;
  24. }
  25.  
  26. Fraction decToFrac(double x) {
  27. bool isNegative = x < 0.0;
  28. x = std::abs(x);
  29.  
  30. if (x > std::numeric_limits<int>::max())
  31. return std::make_pair(isNegative ? -1 : 1, 0);
  32.  
  33. std::ostringstream os;
  34. os.precision(9 - wholeDigits(x)); // int na wiecej nie pozwala
  35. os << std::fixed << x;
  36. std::string numStr = os.str();
  37. int pointPos = numStr.find_last_of('.');
  38. numStr.erase(pointPos, 1);
  39. int fracDigits = numStr.size() - pointPos;
  40.  
  41. int numerator;
  42. std::istringstream is(numStr);
  43. is >> numerator;
  44.  
  45. int denominator = 1;
  46. while (fracDigits--)
  47. denominator *= 10;
  48.  
  49. int d = gcd(numerator, denominator);
  50. numerator /= d;
  51. denominator /= d;
  52.  
  53. if (isNegative)
  54. numerator = -numerator;
  55.  
  56. return std::make_pair(numerator, denominator);
  57. }
  58.  
  59. std::string print(Fraction f) {
  60. std::ostringstream os;
  61. os << f.first << " / " << f.second;
  62. return os.str();
  63. }
  64.  
  65. int main() {
  66. std::cout
  67. << print(decToFrac(1)) << std::endl
  68. << print(decToFrac(100.1)) << std::endl
  69. << print(decToFrac(0.001)) << std::endl
  70. << print(decToFrac(123.456)) << std::endl
  71. << print(decToFrac(-654.321)) << std::endl
  72. << print(decToFrac(1e-15)) << std::endl
  73. << print(decToFrac(1e15)) << std::endl;
  74. }
  75.  
Success #stdin #stdout 0s 3436KB
stdin
Standard input is empty
stdout
1 / 1
1001 / 10
1 / 1000
15432 / 125
-654321 / 1000
0 / 1
1 / 0