Hello @StellaW I think I have the solution to your problem ...
#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;
char a[100];
char nu[100];
int MCD(int A, int B) {
while (A > 0 && B > 0)
if (A > B)
A = A % B;
else
B = B % A;
return A + B;
}
int main() {
cin.getline(a, 100);
int cd = 0;
int pos = 0;
for (auto x : a)
{
if (x != '.')
pos++;
else
break;
}
//este for busca la potencia a elevar
for (int i = pos + 1; i < strlen(a); i++)
{
if (isdigit(a[i]))
cd++;
}
//copia el numerador de la entrada original sin el punto
for (int i = 0, aux = 0; i < strlen(a); i++)
if (isdigit(a[i]))
nu[aux++] = a[i];
double num, den;
//comparamos si ambas cadenas son iguales, contando el 0 como numero...pues esta a la derecha, no como digito significativo sino como digito
if (strlen(a) == strlen(nu) + 1)
{
num = atoi(nu);
den = pow(10, cd);
}
//en caso de que sean iguales qiere decir que no existe el flotante, el numerador sera el propio array nu o a
else if (strlen(a) == strlen(nu))
{
num = atoi(nu);
den = 1;
}
while (MCD(num, den) != 1)
{
int mcd = MCD(num, den);
num /= mcd;
den /= mcd;
}
if (den == 1)
cout << num;
else
cout << num << "/" << den;
return 0;
}
Now I'll give you the explanation of xq the crazy result ... that happened to me too ...
The problem is that the pow function returns a double and you save in den that value that is int ...
Do not tell yourself why instead of giving 100 gives 99 disuclpame I do not know why but it happens to me sometimes and what I do is change it to double ...
And another thing to simplify a fraction always remember to use the MCD Euclide algorithm ... Salu2;)