-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstdntn.c
56 lines (45 loc) · 931 Bytes
/
stdntn.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
/**
* stdntn
*
* a CLI tool to express numeric values in standard notation.
* concepts: algorithms
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
typedef struct {
double a;
intmax_t n;
} StdNtn;
StdNtn express(double x) {
StdNtn ret;
bool neg;
neg = x < 0;
if (neg) x = -x;
ret.a = x;
ret.n = 0;
if (x == 0) return ret;
while (ret.a < 1) {
ret.a *= 10;
ret.n--;
}
while (ret.a >= 10) {
ret.a /= 10;
ret.n++;
}
if (neg) ret.a = -ret.a;
return ret;
}
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "usage: %s <DOUBLE>\n", argv[0]);
return EXIT_FAILURE;
}
double dub = atof(argv[1]);
StdNtn n = express(dub);
printf("express: %f * 10^%jd\n", n.a, n.n);
printf("stdlib: %e\n", dub);
return EXIT_SUCCESS;
}