-
Notifications
You must be signed in to change notification settings - Fork 0
/
DCT2.c
132 lines (111 loc) · 2.5 KB
/
DCT2.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
typedef char *String;
typedef float Number;
int getDecimalLength(Number n1)
{
char c[20], *decimal;
sprintf(c, "%g", n1); // tokenize n1
strtok(c, ".");
decimal = strtok(NULL, ".");
return strlen(decimal);
}
int findGCF(int a, int b)
{
int r;
do
{
r = a % b;
a = b;
b = r;
} while (r > 0);
return a;
}
float getTrailValues(Number n1, int decimalLength, int trail)
{
unsigned int place = pow(10, decimalLength);
int trace = pow(10, trail);
int x = n1 * place;
printf("length: %d, place: %u trail: %u x: %d %f sad\n", decimalLength, place, trace, x, (x % trace) / (float)(place));
return (x % trace) / (place);
}
void simplifyFraction(int fraction[])
{
int GCF = findGCF(fraction[0], fraction[1]);
fraction[0] /= GCF;
fraction[1] /= GCF;
}
void convertToFraction(Number n1, int negative, int trail)
{
int decimalLength = getDecimalLength(n1);
printf("%f %d heree\n", n1, decimalLength);
int fraction[2];
unsigned int place = pow(10, decimalLength);
if (trail == 0)
{
fraction[0] = n1 * place;
fraction[1] = 1 * place;
}
else
{
unsigned int x = pow(10, trail);
float numerator = ((x * n1) - n1) + getTrailValues(n1, decimalLength, trail);
unsigned int z = pow(10, decimalLength - trail);
numerator = roundf(numerator * z) / z;
fraction[1] = x - 1;
if (floorf(numerator) != numerator)
{
place = pow(10, getDecimalLength(numerator));
fraction[0] = numerator * place;
fraction[1] *= place;
printf("%d/%d \n", fraction[0], fraction[1]);
}
else
{
fraction[1] = numerator;
}
}
simplifyFraction(fraction);
if (negative)
{
printf("-%.*f -> -%d/%d", decimalLength, n1, fraction[0], fraction[1]);
}
else
{
printf("%.*f -> %d/%d", decimalLength, n1, fraction[0], fraction[1]);
}
}
int main()
{
Number num;
int negative = 0;
int trail = 0;
int proceed = 0;
while (!proceed)
{
printf("Input a number: ");
scanf("%f", &num);
if (floorf(num) == num)
{
if (num == 0)
{
printf("\nundefined");
return 205; // error signal
}
printf("\nNon-decimal Number alert! Program Exited.");
return 205; // error signal
}
proceed = 1;
}
printf("Enter a trailing number: (0 for non-repeating) \n");
scanf("%d", &trail);
if (num < 0)
{
num *= -1;
negative = 1;
}
convertToFraction(num, negative, trail);
return 0;
}