Created
September 21, 2017 19:43
-
-
Save samclane/9d46a9bb40a6cebee02f456c2cc1e0b8 to your computer and use it in GitHub Desktop.
A special struct for floating point numbers which allows higher accuracy
This file contains 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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <math.h> | |
#define DISPLAY_BUFFER_SIZE 5 | |
typedef struct FixedFloat | |
{ | |
int upper; | |
int lower; | |
int numLowerDigits; | |
}FixedFloat; | |
FixedFloat createFixedFloat(int upper, int lower, int numLowerDigits) | |
{ | |
FixedFloat x = {.upper = upper, .lower = lower, .numLowerDigits = numLowerDigits}; | |
return x; | |
} | |
double getValueFromFixedFloat(const struct FixedFloat fixed_float) | |
{ | |
return fixed_float.upper + (fixed_float.lower / powf(10, fixed_float.numLowerDigits)); | |
} | |
char * getStringFromFixedFloat(const struct FixedFloat fixed_float) | |
{ | |
char * output = malloc(DISPLAY_BUFFER_SIZE); | |
sprintf(output, "%d.%d", fixed_float.upper, fixed_float.lower); | |
return output; | |
} | |
int main() | |
{ | |
FixedFloat y = createFixedFloat(123, 45, 2); | |
printf("%f\n", getValueFromFixedFloat(y)); | |
printf("%f\n", 123 + (45 / powf(10, 2))); | |
printf("%f\n", 123.); | |
printf("%f\n", (45 / powf(10, 2))); | |
printf("%s", getStringFromFixedFloat(y)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment