-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
150 lines (133 loc) · 3.13 KB
/
main.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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
// Jednoduche kalkulacka v C.
// Autor: Erika Dmytrenkova
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
#define QUIT 'q'
/* funkce menu.
Na vyber je:
scitani, odcitani, nasobeni, deleni
Texty pro menu jsou ulozeny v poli stringu.
Vyber dane operace je proveden pomoci zadani znalu operace.
*/
void menu(void)
{
// struktura menu, první nazev, druhý znak - čte z MENU
struct operace
{
char *nazev;
char *znak;
};
// menu array,
const struct operace MENU[] = {
{"scitani", "+"},
{"odcitani", "-"},
{"nasobeni", "*"},
{"deleni", "/"},
{"modulo", "%"},
{"exponent", "^"}};
const int POCET_OPERACI = sizeof(MENU) / sizeof(MENU[0]);
// vypis menu
printf("Menu: \n");
for (int i = 0; i < POCET_OPERACI; i++)
{
printf("(%s) %s \n", MENU[i].znak, MENU[i].nazev);
}
printf("\n");
}
void clear_stdin(void)
{
while (getchar() != '\n')
;
}
void nacti_operaci(char *operace)
{
scanf(" %c", operace);
while (getchar() != '\n')
;
}
void nacti_cislo(float *cislo)
{
while (scanf("%f", cislo) != 1)
{
printf("Zadali jste cislo spatne.\n");
printf("Zadejte cislo znovu: ");
while (getchar() != '\n')
;
}
while (getchar() != '\n')
;
}
// Funkce pro vypocet
bool vypocet(float a, float b, char operace, float *vysledek)
{
switch (operace)
{
case '+':
*vysledek = a + b;
break;
case '-':
*vysledek = a - b;
break;
case '*':
*vysledek = a * b;
break;
case '^':
*vysledek = pow(a, b);
break;
case '%':
if (b == 0)
{
printf("Nelze delit nulou!\n");
return false;
}
*vysledek = (int)a % (int)b;
break;
case '/':
if (b == 0)
{
printf("Nelze delit nulou!\n");
return false;
}
*vysledek = a / b;
break;
default:
printf("Neplatna operace!\n");
return false;
}
return true;
}
// funkce main
int main(void)
{
float a, b, vysledek;
char operace;
char opakovat;
// opakuj dokud uzivatel nezada q
do
{
// vypis menu
menu();
// zadej cisla a operaci
printf("Zadejte operaci: ");
nacti_operaci(&operace);
printf("Zadejte prvni cislo: ");
nacti_cislo(&a);
printf("Zadejte druhe cislo: ");
nacti_cislo(&b);
// vypocet, %.3f - float, za teckou vypise 3 desetinna cisla
if (!vypocet(a, b, operace, &vysledek))
{
printf("Vysledek nelze vypocitat.\n");
}
else
{
printf("Vysledek je: %.3f\n", vysledek);
}
// opakovat?
printf("Pro dalsi vypocet zadejte libovolny znak. (%c pro ukonceni) \n", QUIT);
printf("Zadejte znak: ");
nacti_operaci(&opakovat);
} while (opakovat != QUIT);
return 0;
}