Hello, I'm new here and not quite sure what it means by wrapping code in code tags so for my future posts can someone let me know how this should have been formatted so it would be a correct post? My question is I have a program I am writing to act like a calculator, which it does, my only issue is when I divide by zero I end up with an output that includes 1.#J and I'm not sure why. Can anyone give me a hint? Everything else works properly. Here is the code:


// This program mimics a calculator using the values that the user inputs
// as well as the operand the user inputs.

//Header Declaration
#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
// Variable Declaration
float Numbera;
float Numberb;
char operand;
int Numberc;
float answera;
float answerb;
float answerc;
float answerd;

//Set format of output to two decimal places
cout << fixed << showpoint;
cout << setprecision (2);

// Request input from user
cout << "Enter two numbers: ";
cin >> Numbera >> Numberb;
cout << endl;

cout << "Enter a operator: + <addition>, - <subtraction>, * <multiplication>, / <division>:";
cin >> operand;
cout << endl;

// Use switch structures to evaluate
switch (operand)
{
case '+': answera = Numbera + Numberb;
cout << answera << endl;
break;

case '-': answerb = Numbera - Numberb;
cout << answerb << endl;
break;

case '*': answerc = Numbera * Numberb ;
cout << answerc << endl;
break;

case '/': answerd = Numbera / Numberb;
cout << answerd <<
endl;
break;

}
if (Numberb == 0 && operand == '/')
cout << "ERROR" <<
cout << "Cannot divide by 0" << endl;
//Required statement for viewing
system ("pause");

return 0;
}

You have most of the code written to solve your problem already. You just need to put it in the right spot.
Re-write your division case as follows:

case '/': answerd = Numbera / Numberb;
if (Numberb == 0 )
{
            cout << "ERROR Cannot divide by 0" << endl;
            break;
}
cout << answerd << endl;
break;

This way the answer will never be output if the second number is 0 and the operator is division.
Also, you don't need anything after the switch statement besides the system pause. Hope that helps.

To use code tags, press the code button when you want to post code. Dani really can't make it any easier than it is now. ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.