[ create a new paste ] login | about

Link: http://codepad.org/m15Ytnz7    [ raw code | output | fork ]

AaronMiller - C++, pasted on Jul 6:
/*
    THEORY: Converting a real number to a "percentage" and
            finding the greatest common factor between the
            percentage and the base-percentage (in this case
            the value * ACCURACY and ACCURACY) will result
            in an easy to use method of finding a fraction
            from a real number. For example, the greatest
            common factor of 50 and 100 is 50. Divide 50 by
            50 and the result is 1. Divide 100 by 50 and the
            result is 2. Therefore, the fraction is 1/2. 50
            and 100 were computed from 0.5 as follows:
               d = 100
               n = 0.5*d = 50
            There seems to be an issue when computing 1/3.
*/

#include <stdio.h>

#define ACCURACY 1000
#define MakeFrac(a,b) (((double)a)/((double)b))

unsigned int findGcf(unsigned int a, unsigned int b)
{
    while(a != b)
    {
        if (a > b)
            a -= a;
        else if (b > a)
            b -= a;
    }
    return a;
}

void calcFraction(double value, unsigned int *pNumerator, unsigned int *pDenominator)
{
    unsigned int n, d, gcf;
    n = (unsigned int)(value * ((double)ACCURACY));
    d = ACCURACY;
    gcf = findGcf(n, d);
    n /= gcf;
    d /= gcf;
    *pNumerator = n;
    *pDenominator = d;
}

int main()
{
    unsigned int a, b;
    a = 1250;
    b = 5000;
    printf("gcf of (%u,%u) = %u\n", a, b, findGcf(a, b));
    calcFraction(MakeFrac(a,b), &a, &b);
    printf("fraction = %u/%u\n", a, b);
    return 0;
}


Output:
1
2
gcf of (1250,5000) = 1250
fraction = 1/4


Create a new paste based on this one


Comments: