I got the jumping into c++ book and i've met functions again. This time, i kinda understand it (this is the 5th book i'm using to learn c++), last problem was vectors so i decided i needed a new book (this was after 2 failed functions learning and 1 failed array learning).
In this book, functions comes before arrays and the first time i met functions was in the cplusplus.com pdf, then in programming principles book which i just switched from and i had no idea what so ever what it did/what they were talking about, so i changed books. Now i've met it again and this book explains better.
I was writing calculator program and it doesn't seem right, it does everything right but it's like 2/3x more code than doing everything in
int main()
. How would you use functions in a simple (+, -, /, *) calculator program?
My code is below.
Thanks.
#include <iostream>
#include <string>
double calc_add (double a, double B)/>
{
return a+b;
}
double calc_minus(double a, double B)/>
{
return a-b;
}
double calc_multiply(double a, double B)/>
{
return a*b;
}
double calc_divide(double a, double B)/>
{
return a/b;
}
void calculator ()
{
double x = 0;
double y = 0;
char unit = ' ';
std::string QUIT;
do
{
std::cout <<"CALCULATOR \n\n";
std::cout <<"Enter operation: ";
std::cin >> x >> unit >> y;
switch (unit)
{
case '+':
std::cout << calc_add(x, y);
break;
case '-':
std::cout << calc_minus(x, y);
break;
case '*':
std::cout << calc_multiply(x, y);
break;
case '/':
std::cout << calc_divide(x,y);
break;
}
std::cout << "\n\nDo you want to quit: ";
std::cin >> QUIT;
if (QUIT == "No")
{
system ("cls")
)
}
while (QUIT == "No");
}
int main()
{
calculator();
return 0;
}
No indentation (no tab key on mobile).