Error with Irreducible Fractions

0

I am doing a program that when I receive a number with decimals, I take it to a simplified fraction. I did some tests and he does it well, but when I enter 0.24 he gives me a very high value.

int main(){

    float n;
    int aux;
    float dec = 1.0;
    int c = 0;

    cin >> n; cin.ignore();

    while(dec != 0){

        n = n*10.0;
        aux = n;
        dec = n - aux;
        c++;        
    }

    int den = pow(10, c);

    //Simplificando

    while(aux%2==0 && den%2==0){
        aux = aux / 2;
        den = den / 2;
    }

    while(aux%5==0 && den%5==0){
        aux = aux / 5;
        den = den / 5;
    }

    cout << aux << "/" << den << endl;

    return(0);
}
    
asked by StellaW 15.12.2018 в 20:51
source

1 answer

0

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;)

    
answered by 16.12.2018 / 03:05
source