calculator

if you will make a calculator program with */± operations
what corner cases should you consider when you dont want the program to crash
one way is to be alert when using / because division by zero is not allowed. anything else to add?

Make sure that your data types can hold large values, or otherwise, there will be trouble if the user enters large numbers. It’s best if you restrict the number of digits that can be entered to reduce this risk.

The rounding of floats and doubles is also something you should consider.

Note that these suggestions are for a bit advanced calculator. If you just want to make a calculator for beginners, then just restrict the size of input and check for the division by zero, that should be enough.

Seeing your code, the error seems to be just as explained by @rjohari23 's answer, you need to use float ( or double ), otherwise, decimal points will be ignored by int’s. So, when you enter a denominator greater than the numerator, you get output as 0, which is surely wrong.

So, change your two variables q and w to float ( or double ).

1 Like

@ramher237, your code will give Wrong Answer when num1 < num2 i.e. q < w.

For example:

for input:

1 3 /

your code’s output:

0

expected output ( as a real calculator would produce ):

0.333333…

Try using float or double instead of long int and then check the output.

int main() {

   	char a;
   	float q,w;
   	while(cin >> q >> w >> a)
   	{
    	if ( a=='+' )
    		cout << q+w << endl;
   		else if ( a=='-' )
    		cout << q-w << endl;
   		else if ( a=='*' )
    		cout << q*w << endl;
   		else if ( a=='/' )
   		{
       		if ( w==0 )
        		cout << "MALFORMED" << endl;
       		else
        		cout << q/w << endl;
   		}

    	else
        	cout << "MALFORMED" << endl;
   	}
   	return 0;
}

Link to your working code.

2 Likes

this is for a homework meant for beginners, but even though im considering your advice, i still get a wrong answer for an input of our prof

@ramher237 , which language do you use ?

@ramher237

Can you paste your code here as you said your code is giving WA for some input to that we can spot the missing case…

1 Like

#include
#include
using namespace std;

int main()
{

   char a;
   long int q,w;
   while(cin >> q >> w >> a)
   {
    if(a == '+')
    cout << q+w << endl;
   else if(a == '-')
    cout << q-w << endl;
   else if(a == '*')
    cout << q*w << endl;
   else if(a == '/')
   {
       if(w == 0)
        cout << "MALFORMED" << endl;
       else
        cout << q/w << endl;
   }

    else
        cout << "MALFORMED" << endl;
   }

}

the input goes by
number___number___operation(/,*,+,-)

unsigned long long int doesnt work either