#include <iostream>
#include <cmath> // std::round, std::floor
#include <numeric> // std::gcd
// Simple method: multiply by powers of 10
std::pair<int, int> floatToFraction(double num, int maxDenominator = 1000000) {
if (num == 0) return {0, 1};
// Handle negative numbers
bool isNegative = num < 0;
num = std::abs(num);
// Find the number of decimal places
int denominator = 1;
double temp = num;
// Multiply by powers of 10 until we get a whole number
while (temp != std::floor(temp) && denominator <= maxDenominator) {
temp *= 10;
denominator *= 10;
}
int numerator = static_cast<int>(std::round(temp));
// Simplify the fraction
int commonFactor = std::gcd(numerator, denominator);
numerator /= commonFactor;
denominator /= commonFactor;
if (isNegative) numerator = -numerator;
return {numerator, denominator};
}
int main() {
double numbers[] = {0.5, 0.25, 0.75, 0.333333, 0.125, 0.1, -0.6};
std::cout << "Float to Fraction Conversion:\n";
std::cout << "=============================\n";
for (double num : numbers) {
auto fraction = floatToFraction(num);
std::cout << num << " = " << fraction.first << "/" << fraction.second << std::endl;
}
}
/*
run:
Float to Fraction Conversion:
=============================
0.5 = 1/2
0.25 = 1/4
0.75 = 3/4
0.333333 = 333333/1000000
0.125 = 1/8
0.1 = 1/10
-0.6 = -3/5
*/