-
Notifications
You must be signed in to change notification settings - Fork 124
/
exercise08.c
97 lines (79 loc) · 2.08 KB
/
exercise08.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
// C Primer Plus
// Chapter 8 Exercise 8
// Write a program that shows you a menu offering you the choice of addition,
// subtraction, multiplication, or division. After getting your choice, the
// program asks for two numbers, then performs the requested operation. The
// program should accept only the offered menu choices. It should use type
// float for the numbers and allow the user to try again if he or she fails to
// enter a number. In the case of division, the program should prompt the user
// to enter a new value if 0 is entered as the value for the second number.
#include <stdio.h>
#include <ctype.h>
int get_first(void);
void print_menu(void);
float get_number(void);
int main(void)
{
int operation;
float num1, num2;
print_menu();
while ((operation = get_first()) != 'q')
{
printf("Enter first number: ");
num1 = get_number();
printf("Enter second number: ");
num2 = get_number();
switch (operation)
{
case ('a') :
printf("%.3f + %.3f = %.3f\n", num1, num2, num1 + num2);
break;
case ('s') :
printf("%.3f - %.3f = %.3f\n", num1, num2, num1 - num2);
break;
case ('m') :
printf("%.3f * %.3f = %.3f\n", num1, num2, num1 * num2);
break;
case ('d') :
while (num2 == 0)
{
printf("Enter a number other than 0: ");
num2 = get_number();
}
printf("%.3f / %.3f = %.3f\n", num1, num2, num1 / num2);
break;
default :
printf("I do not recognize that input. Try again.");
}
print_menu();
}
}
int get_first(void)
{
// return first non-whitespace character
int ch;
do ch = getchar(); while (isspace(ch));
while (getchar() != '\n')
;
return ch;
}
void print_menu(void)
{
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply d. divide\n");
printf("q. quit\n");
}
float get_number(void)
{
int ch;
float num;
while (scanf("%f", &num) != 1)
{
while ((ch = getchar()) != '\n') // echo user input and clear stream
putchar(ch);
printf(" is not a number.\n");
printf("Please enter a number, such as 2.5, -1.78E8, or 3: ");
}
return num;
}