-
Notifications
You must be signed in to change notification settings - Fork 124
/
exercise02-b.c
70 lines (60 loc) · 1.31 KB
/
exercise02-b.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
#include <stdio.h>
#include "exercise02.h"
#define METRIC 0
#define US 1
static int mode;
static double distance;
static double fuel;
void clear_input_stream(void)
{
while (getchar() != '\n')
continue;
}
void set_mode(int new_mode)
{
extern int mode;
if (new_mode == METRIC || new_mode == US)
mode = new_mode;
else
printf("Invalid mode specified. Mode %d(%s) used.\n",
mode, mode == METRIC ? "metric" : "US");
}
void get_info(void)
{
printf("Enter distance travelled in %s: ",
mode == METRIC ? "kilometers" : "miles");
while (scanf("%lf", &distance) != 1)
{
clear_input_stream();
printf("Invalid input. Enter distance travelled in %s: ",
mode == METRIC ? "kilometers" : "miles");
}
printf("Enter fuel consumed in %s: ",
mode == METRIC ? "liters" : "gallons");
while (scanf("%lf", &fuel) != 1)
{
clear_input_stream();
printf("Invalid input. Enter fuel consumed in %s: ",
mode == METRIC ? "liters" : "gallons");
}
}
void show_info(void)
{
double efficiency;
if (mode == METRIC)
{
efficiency = fuel / distance * 100;
printf("Fuel consumption is %.3f liters per 100 kilometers.\n",
efficiency);
}
else if (mode == US)
{
efficiency = distance / fuel;
printf("Fuel consumption is %.3f miles per gallon.\n",
efficiency);
}
else
{
printf("Error. Invalid mode: %d\n", mode);
}
}