Basic Calculator. Suggest improvements.

Hey guys so I have beem working on my coding format for quite a while! And please suggest any improvements to this basic program so I can learn from them! Thanks!

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
//Example Program
//Calculator.exe

#include <iostream>
#include <cmath>
#include <string>
using namespace std;

int main ()
{
cout << "Welcome to the calculator program!" << endl;

cout << "Please put in the decimal only when you want the result to be in decimal form" << endl;

float x;
float y;
float result;
float quo;

string choice;
string end;

do
{
cout << "What type of calculation do you want to do?" << endl;

cout << "Enter 'multiply' for multiplication" << endl;

cout << "Enter 'divide' for division" << endl;

cout << "Enter 'substract' for substraction" << endl;

cout << "Enter 'add' for addition" << endl;

cout << "Enter 'sqrt' for square root" << endl;

cin >> choice;

if (choice == "multiply")
{
cout << "Enter the first number you want to multiply" << endl;

cin >> x;

cout << "Enter the number you want to multiply the first number with" << endl;

cin >> y;

result = (x * y);

cout << "Result: " << result << endl;
}

else if (choice == "divide")
{
cout << "Enter dividend" << endl;

cin >> x;

cout << "Enter divisor" << endl;

cin >> y;

result = quo = (x / y);

cout << "Quotient: " << quo << endl;

result = (x - (quo * y)); 

cout << "Remainder: " << result << endl;
}

else if (choice == "substract")
{
cout << "Enter the amount to be substracted from" << endl;

cin >> x;

cout << "Enter the amount to be substracted" << endl;

cin >> y;

result = (x - y);

cout << "Result: " << result << endl;
}

else if (choice == "add")
{
cout << "Enter the first number to be added" << endl;

cin >> x;

cout << "Enter the second number to be added" << endl;

cin >> y;

result = (x + y);

cout << "Result: " << result << endl;
}

else if (choice == "sqrt")
{
cout << "Enter the number you want the root of" << endl;

cin >> x;

result = sqrt (x);

cout << "Result: " << result << endl;
}

else
{
cout << "Wrong choice!" << endl;
}

cout << "Do you want to restart the program? (y / n)" << endl;

cin >> end;
}
while (end != "n");

cin.get ();

return 0;
}  
I think you should add indentation to your code to make it easier to read.
closed account (1vD3vCM9)
there is an awesome thing that will make it easier to program
called Switch, it can save a lot of: if, else if, else - lines for you.
Example:
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
#include <iostream>
#include <conio.h>
	int a, b;
char operation;

int main(int argc, char** argv) {
	std::cout << "First Number: ";
	std::cin >> a;
	std::cout << "Operation: ";
	std::cin >> operation;
	std::cout << "Second Number: ";
	std::cin >> b;
	switch (operation)
	{
	case '+':
		std::cout << "Result: " << a << operation << b << "=" << a + b << std::endl;
		break;
	case '-':
		std::cout << "Result: " << a << operation << b << "=" << a - b << std::endl;
		break;
	case '*':
		std::cout << "Result: " << a << operation << b << "=" << a*b << std::endl;
		break;
	case '/':
		std::cout << "Result: " << a << operation << b << "=" << a / b << std::endl;
		break;
	default:
		std::cout << "The Operation You Have Chose Doesn't Exit/Is Invalid\n";
		std::cout << "Press Any Key To Exit...\n";
		_getch();
		break;
	}
	std::cout << "Press Any Key To Exit...\n";
	_getch();
	return(0);
}


Last edited on
I thought I did the braces properly :'(
Hi,

Right oh, you asked for it, here goes ....... :+)

Avoid having line 7, just put std:: before each std thing. Believe me, it's the best way, all the experts do that. Google it.

Don't use std::endl , it flushes the buffer and could be inefficient for a larger program. Put '\n' in your output:

std::cout << "Welcome to the calculator program!\n";

Use functions. A function should do 1 conceptual thing, and shouldn't be any longer than 40LOC, this includes main within reason. So the menu, each +-/* operation should all have their own functions. Getting the input for x and y should be a function too, then you don't have to repeat that code throughout the program. Using functions aids understanding, it's a simple form of abstraction. Choose meaningful names for them, and provide a comment on what the function does.

Delay the declaration of a variable until you have a sensible value to initialise with. Do the declaration and initialisation on one line. Write a comment about it's expected valid ranges. Choose a meaningful name for variables, it's a misnomer to over abbreviate everything. For example, quotient instead of quo

Prefer double instead of float, unless using some graphics library which requires it. Float is easily exceeded, that is why double is the default for literals.

Prefer a single char or int as a choice value. Using std::string makes your code fail if 1 char is the wrong case, or the word is misspelt, or otherwise not the same as your code. Use the std::toupper or std::tolower on the char, then you you don't have to worry about the upper / lower case of it. Then you can use a switch with a default case to catch bad input. enum can also be used for the individual cases. Compiler warnings can be turned on if not all the enum's have a matching case. Each case: of the switch should call a function.

I am not a fan of do loops. All 3 looping constructs can be converted from one to another, maybe at the price of an extra variable. So I prefer to use a while loop in this situation. Just because one wants the code to execute at least once should not be a sole consideration for using a do loop IMO. You can make use of a bool Quit value to control the loop.

Why does everyone forget to check for division by zero? One must consider anything that may go wrong, and write code to defend against those things.

A sqrt function should check to see if the argument is positive, otherwise the program will crash with an un-handled exception

Your code also needs indentation, your editor in your IDE should do this for you, auto-magiacally.

Good Luck, hopefully you found all this helpful :+)

Edit:

http://www.cplusplus.com/doc/tutorial/functions/

Last edited on
@Oren

Thanks! I'll try to play around switches more! They are really difficult to work with!

@TheIdeasMan

Thanks for the corrections! So if i declare functions before int main () can I use them in the int main ()? Also I'll work on chars more! Also what things come under the std:: library?

I tried double int something; but it gives an error when the user enters decimal values or includes decimals. Btw why doesn't this work?
1
2
float remainder;
remainder = (dividend % divisor);
the error says that the operation is invalid.
Thanks! I'll try to play around switches more! They are really difficult to work with!


They are actually a very easy and useful tool.

So if i declare functions before int main () can I use them in the int main ()


Yes, that is the normal layout of the file #include s , function declarations, main, function definitions.

I modified the example in the link I gave you earlier:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// function example
#include <iostream>
using namespace std;

// function declaration
// this must match the definition below
int addition (const int a, const int b); 

int main ()
{
  int z;
  z = addition (5,3);
  std::cout << "The result is " << z;
}

// function definition, parameters are const, we don't change them in the function
int addition (const int a, const int b)
{
  int r = a+b;
  
  return r;
}


I tried double int something; but it gives an error when the user enters decimal values or includes decimals.


It's a matter of understanding the different types, you were trying to have two types rather than one. double something = 10.0;

the error says that the operation is invalid.


modulus is for integers.

Also what things come under the std:: library?


Everything in the STL (Standard Template Library) exists in the std namespace. Every class, function, container, algorithm, manipulator, iterator etc.

So to start with:

1
2
3
4
5
6
7
std::cout
std::cin
std::setprecision
std::setw
std::string
std::vector
std::size_t


You will get used to it as you go along, the compiler will tell you if you miss one.


So if i declare functions before int main () can I use them in the int main ()?

Absolutely.

Also what things come under the std:: library?

Just about everything that comes from a standard C++ include file.
http://www.cplusplus.com/reference/

I tried double int something; but it gives an error
double int is not a valid type. Just use double.

why doesn't this work?
1
2
float remainder;
remainder = (dividend % divisor)

What are the types of dividend and divisor?

Last edited on
closed account (1vD3vCM9)
speaking of which, can someone really explain why not to do: using namespace std;?
@TheIdeasMan
Thanks alot! The thing is I always get confused with the switch layout.

So I'll then utilize functions for arithematic operations!

@AbstractionAnon
Thanks! Those are all floats.
Topic archived. No new replies allowed.