Created
May 22, 2011 05:03
-
-
Save CarterA/985193 to your computer and use it in GitHub Desktop.
Frack!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // frack.c | |
| // frack | |
| // | |
| // Created by Carter Allen on 5/21/11. | |
| // Copyright 2011 Opt-6 Products, LLC. All rights reserved. | |
| // | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <math.h> | |
| #define MAX_DENOMINATOR 1000 | |
| typedef struct { | |
| int numerator; | |
| int denominator; | |
| } Fraction; | |
| Fraction frackify(double input) { | |
| double tolerance = 0.0001; | |
| int intPart = floorf(input); | |
| double fracPart = input - intPart; | |
| Fraction result; | |
| result.numerator = input * MAX_DENOMINATOR; | |
| result.denominator = 1; | |
| for (result.denominator = 1; result.denominator < MAX_DENOMINATOR; result.denominator++) { | |
| if (fabs(result.denominator * fracPart - round(result.denominator * fracPart)) <= tolerance) { | |
| result.numerator = round(input * result.denominator); | |
| break; | |
| } | |
| } | |
| return result; | |
| } | |
| int main(int argc, const char * argv[]) { | |
| double input = atof(argv[1]); | |
| Fraction result = frackify(input); | |
| printf("%d/%d\n", result.numerator, result.denominator); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment