Help with simple calculator (if - else)

The teacher wanted us to make a simple calculator. But he wants it as short as possible. Can I go shorter than these? Input: 3+5 Output: 3+5=8 is a must.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  #include <iostream>
using namespace std;
int main() {
    double num1, num2, res {};
    char opr {};
    cout << "Enter calculation: ";
    cin >> num1 >> opr >> num2;
    if (opr == '+' || opr == '-' || opr == '*' || opr == '/' ) {
        if (opr == '+')
            res = num1 + num2;
        else if (opr == '-')
            res = num1 - num2;
        else if (opr == '*')
            res = num1 * num2;
        else
            res = num1 / num2;
    cout << "Answer: " << num1 << opr << num2 << "=" << res << endl;
    } else
        cout << "Wrong operator!" << endl;
    return 0;
}
Shorter by what metric? Number of characters? Number of lines? Number of semi-colons? Number of assembly instructions output? Your code looks fine to me...

It is important to note, shorter does not mean better. It's really case-by-case. But anyway, those weren't rhetoric questions, I actually don't understand.

PS: Your indentation on line 17 is wrong.
Last edited on
shorter code has merits, so its a good exercise, but there is a happy medium. Too short can be unreadable... the biggest problem with long code is it has other problems, like unnecessary work or extra complexity that isn't needed, the first being a coder error of sorts and the second being just as unreadable as too short. Most code should look like what you have: easy to follow and easy to work on if it needs changes.

that said, I can take a crack at it.

does this work for you?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
int main() 
{
    double num2,res{};
    char opr {};
    cout << "Enter calculation: ";
    cin >> res >> opr >> num2;	
	string out[2]{"Answer: " + to_string(res) + " " + opr + " " + to_string(num2) + " = ", "Wrong operator!\n"};
	 char isadd{-1*(opr == '-') + (opr == '+')}, ismul{(opr == '*') + (opr == '/')};		            
		res += num2*(isadd);        
		num2 = (opr=='/')/num2 + num2*(opr == '*');
		res *= num2*ismul + !ismul;		
		out[0] += to_string(res)+"\n";
		cout << out[!(isadd || ismul)];
}


you could also try a goto that rolls the * and / both into addition. Hmm.
Last edited on
wants it as short as possible


1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <cstring>

int main() {
    constexpr const char* oprs {"+-*/"};
    double num1 {}, num2 {};
    char opr {};

    std::cout << "Enter calculation: ";
    std::cin >> num1 >> opr >> num2;

    strchr(oprs, opr) ? std::cout << "Answer: " << num1 << opr << num2 << "=" << (opr == '+') * (num1 + num2) + (opr == '-') * (num1 - num2) + (opr == '*') * (num1 * num2) + (opr == '/') * (num1 / num2) << '\n' : std::cout << "Invalid operator\n";
}

Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;
int main()
{
   double num1, num2, res = 0.0;
   char opr;
   bool bad = false;
   cout << "Enter calculation: ";
   cin >> num1 >> opr >> num2;
   switch( opr )
   {
      case '+' : res = num1 + num2;   break;
      case '-' : res = num1 - num2;   break;
      case '*' : res = num1 * num2;   break;
      case '/' : res = num1 / num2;   break;      
      default: bad = true;
   }
   if ( bad ) cout << "Bad op\n";
   else       cout << num1 << opr << num2 << "=" << res << '\n';
}



I guess in theory you could do
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;
int main()
{
   double num1, num2, res = 0.0;
   char opr;
   bool bad = false;
   cout << "Enter calculation: ";
   cin >> num1 >> opr >> num2;
   res = opr == '+' ? num1 + num2 : opr == '-' ? num1 - num2 : opr == '*' ? num1 * num2 : opr == '/' ? num1 / num2 : bad = true;
   if ( bad ) cout << "Bad op\n";
   else       cout << num1 << opr << num2 << "=" << res << '\n';
}
Last edited on
Not to be taken too seriously ...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <map>
using namespace std;

#define OP( x ) []( double a, double b ){ return ( x ); }
map<char, double(*)(double,double)> F = { {'+',OP(a+b)}, {'-',OP(a-b)}, {'*',OP(a*b)},{'/',OP(a/b)} };

int main()
{
   double num1, num2;
   char opr;
   cout << "Enter calculation: ";
   cin >> num1 >> opr >> num2;
   if ( F.find( opr ) != F.end() ) cout << F[opr]( num1, num2 ) << '\n';
   else                            cout << "Bad op\n";
}
Oh, of course... building and stealing from above..

1
2
3
4
5
6
7
8
9
10
11
int main() 
{
    double num2,res{};
    char opr {};
    cout << "Enter calculation: ";
    cin >> res >> opr >> num2;	
	string out[2]{"Answer: " + to_string(res) + " " + opr + " " + to_string(num2) + " = ", "Wrong operator!\n"};
	map<char, double> tbl = { {'+',res+num2}, {'-',res-num2}, {'*',res*num2},{'/',res/num2} };
	out[0] += to_string( tbl.find(opr)!=tbl.end()? tbl[opr] : 0.0)+"\n";
	cout << out[(tbl.find(opr)==tbl.end())];
}


and that gets you down to the question of what is being counted.
that is 4 "lines of code" with 4 lines of variable declarations and the rest is your includes (you can cut the using out and give the code an std to save that line) and main + brackets.
but its still a lot of characters.
Last edited on
@Ganado @jonnin @seeplus @lastchance (Idk how to mention on this site but I hope this works.)

Thanks for your all kind helps. I'm such a beginner. So nowadays it's hard for me to understand what you guys wrote down here.

And it looks like our teacher was not wanting a shorter code. He didn't give any feedback about revisions and we thought it would be a shorter code.

He was like wanting additions like you can't divide with 0 and 0/0 is an undefined thing. Idk really but we'll see tomorrow. And sorry for bothering anyone who came up with this topic.

good luck!
I was trying to say that originally ... too short usually hard to follow/read.
in short .. hah .. it computes all the values and then picks the one the user wanted if any. So it is wasteful on top of being unreadable. You can circle back to it for a laugh when you are farther along.

As for the others..

if(num1 == 0 && num2 ==0)
// 0/0 message or action
else //you don't want both actions, so putting else here prevents that.
if (num2 == 0)
//then divide by zero action (cout something?)

and similar for any other conditions you want to add -- you can get fancy and detect overflow / underflow perhaps, not much else to do on these.
Topic archived. No new replies allowed.