Calculator in C++

Hey I'm trying to make a basic calculator in C++ and it doesn't seem to be working... (I'm using devcpp) My code is below, if you can help me please do.

#include <iostream.h>
//My Calculator

int main()
{
double num, den, result;
char op;
do {
cout << "n/calculator - Enter: ";
cin >> num;
cout << "Enter +,-,*";
cin >> op;
cout << "Enter Another Number";
cin << den;
if (op=='+') result=num+den;
if (op=='-') result=num-den;
if (op=='*') result=num*den;
if (op=='/') result=num/den;
cout << result;
}
while (op!='e');
return0;
}
first, please always use code tags. And, you didn't use cin correctly on line 11. Make these changes to the code, and you're good!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int main()
{
double num, den, result;
char op;
do {
cout << "n/calculator - Enter: \n";
cin >> num;
cout << "Enter +,-,*\n";
cin >> op;
cout << "Enter Another Number\n";
cin >> den;
if (op=='+') result=num+den;
if (op=='-') result=num-den;
if (op=='*') result=num*den;
if (op=='/') result=num/den;
cout << result << "\n";
}
while (op!='e');
return 0;
}
Use if, else if, and else statements, instead of a bunch of different if statements. The way you have it, it would check with every statements if you use else if, it will only check until it finds a statement that is true. Also, you should a way to check if the user entered valid input, and if they don't give them an error.

Edit: You should also use new lines (\n) after all of your outputs.
Last edited on
1
2
3
4
5
6
#include <iostream> // newer version
using namespace std;//or std::cout, std::cin

cout << "Enter +,-,*"; // missing character for divide operation
cin << den; // should be >> for cin
if (op=='/') result=num/den; // probably want check for dividing by zero 


while (op!='e');
It's not clear where the user is going to enter e (to exit?). After you output the result I'd output something like "Enter c to continue or e to exit". So if they enter 'e', the loop terminates.
Last edited on
@geniusberry what do you mean codetags?
[code]this is some code[/code] = this is some code

When you're in edit mode for a post, there's a table of format tags over on the right side.

Highlight your code and click the <> button and that'll format your code. That and good indentation in the first place makes it easier to read the code :) You can also type opening and closing code tags manually
[code] your code here [/code]
.

The button to right of the the code tag lets you
format output
Last edited on
Topic archived. No new replies allowed.