If you want two multiply two fractions, you can multiply the nominators, denominators, then simplify the result by dividing the resulting elements by the gcd. The gcd can be calculated by Euclide algorithm. If you want to multiply two float numbers which are not available as fractions, you can first convert each of them to a close fraction. For a given precision 1/N, you can multiply each float by N, round it and get the numerator, N being the denominator.
#include <iostream>
#include <string>
#include <tuple>
// Euclide algorithm
int gcd (int a, int b) {
if (a < b) std::swap (a, b);
while (b > 0) {
int t = b;
b = a % b;
a = t;
}
return a;
}
// multiplication float * int
double mult_float_int (double a, int b) {
double res = 0;
for (int i = 0; i < b; i++)
res += a;
return res;
}
// double -> fraction
std::pair<int,int> float2frac (double x, int N) {
int a = mult_float_int (x, N);
int g = gcd (a, N);
if (g == 0) g = 1;
return std::make_pair (a/g, N/g);
}
// multiplication a * b
int mult_int (int a, int b) {
int res = 0;
if (a < b) std::swap (a, b);
for (int i = 0; i < b; i++)
res += a;
return res;
}
// multiplication a0/b0 * a1/b1
std::pair<int,int> mult_frac (int a0, int b0, int a1, int b1) {
int a2 = mult_int (a0, a1);
int b2 = mult_int (b0, b1);
int g = gcd (a2, b2);
if (g == 0) g = 1;
return std::make_pair (a2/g, b2/g);
}
int main()
{
const int N = 100000;
int a0, b0, a1, b1, a2, b2;
double x, y;
std::cout << "enter x : ";
std::cin >> x;
std::cout << "enter y : ";
std::cin >> y;
std::tie (a0, b0) = float2frac (x, N);
std::tie (a1, b1) = float2frac (y, N);
std::tie (a2, b2) = mult_frac (a0, b0, a1, b1);
std::cout << x << " * " << y << " = " << a2 << "/" << b2 << "\n";
std::cout << "Error = " << x*y - double(a2)/b2 << "\n";
return 0;
}
Demo:
Process started (PID=7400) >>>
enter x : 1.25
enter y : 3.27
1.25 * 3.27 = 327/80
Error = 2.21177e-017
Note: the classical way to approximate a float with a fraction by multiplication by N was recalled by user463035818 first. A theoretical better way to approximate by a fraction is using continued fractions, see for example Fractions instead of decimals. However, doing it without multiplication or division is a challenge ...