Telling my calculator to not divide by zero - c++

I am making a calculator in C++ and it works fine except when I divide by zero. So I have an if statement saying to give the message "Error Divide buy zero" when a number is divide by zero. However the program still crashes.
Here is my code
#include <iostream>
using namespace std;
int main()
{
int a, b, d, s;
d == a/b
cout << "Enter first number\n";
cin >> a;
cout << "Enter second number\n";
cin >> b;
cout << "Select the operation you want\n";
cout << "1.Addition\n";
cout << "2.Subtraction\n";
cout << "3.Multiplication\n";
cout << "4.Division\n";
cin >> s;
switch (s)
{
case 1: cout << "Addition Selected\n"; a+b << endl; break;
case 2: cout << "Subtraction Selected\n"; a-b << endl; break;
case 3: cout << "Addition Selected\n"; a*b << endl; break;
case 4:
if (b==0)
{
cout << "Error Divide by Zero"<< endl;
}
else
{
cout << d << endl;
}
break;
default: cout << "Invalid Selection" << endl;
}
return 0;
}
On a secondary note when I select an operation it doesn't say that it was selected.

Your code has a lot of syntax errors.
Perhaps this can help you. This smartly avoids divide by zero and prints error message also.
#include <iostream>
using namespace std;
int main() {
int n1, n2, ans;
char op;
cin >> n1 >> op >> n2;
switch (op) {
case '+':
ans = n1 + n2;
break;
case '-':
ans = n1 - n2;
break;
case '*':
ans = n1 * n2;
break;
case '/':
if (n2) {
ans = n1 / n2;
break;
}
default:
cerr << "Invalid Input" << endl;
return 1;
}
cout << ans;
return 0;
}
See http://ideone.com/wa8QJG demo.

Your line
d == a/b;
Needs to be
d = a/b;
and it needs to move within the "else" clause. Otherwise the division by 0 error occurs before the print explaining the error.
You are also missing a print for the divide case and should add that.

There are many typos/syntax errors in your code.
Here is a working solution close to your code:
int main()
{
int a, b, d, s;
cout << "Enter first number\n";
cin >> a;
cout << "Enter second number\n";
cin >> b;
cout << "Select the operation you want\n";
cout << "1.Addition\n";
cout << "2.Subtraction\n";
cout << "3.Multiplication\n";
cout << "4.Division\n";
cin >> s;
switch( s )
{
case 1:
cout << "Addition Selected\n" << a + b << endl;
break;
case 2:
cout << "Subtraction Selected\n" << a - b << endl;
break;
case 3:
cout << "Multiplication Selected\n" << a * b << endl;
break;
case 4:
if( b == 0 )
{
cout << "Error Divide by Zero" << endl;
}
else
{
d = a / b;
cout << d << endl;
}
break;
default:
cout << "Invalid Selection" << endl;
}
return 0;
}

Related

Using sqrt() funtion in switch case

#include<iostream>
#include<cmath>
using namespace std;
int main(void)
{
float a,b,y,z,x;
char chart;
cout<< "Enter Operator";
cin>>chart;
cout<<"\n\t Enter First Number\n";
cin>>a;
cout<<"\n\t Enter Second Number\n";
cin>>b;
switch (chart)
{
case '+':
a+b;
cout<<"\n\t"<<a+b<<"\n";
break;
case '-':
cout<<"\n\t"<<a-b<<"\n";
break;
case '*' :
cout<<"\n\t"<<a*b<<"\n";
break;
case '/':
cout<<"\n\t"<<a/b<<"\n";
break;
default:
cout<< " \nThe operator is not supported\n\n\n\n\n";
break;
}
return 0;}
I am a beginner and new to C++ ]. this is my code for a simple calculator, I want to know how to use the sqrt() funtion in switch case. Any help will be appreciated. Thank you. Also please suggest how to make this code better
Try out this one little bit modified on the basis of unary and binary operators you can also alter it according to your need.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int op;
cout << "Enter 1 for unary operation or 2 for binary operation: ";
cin >> op;
if (op==1)
{
int operation;
int num;
cout << "\nEnter number: ";
cin >> num;
cout << "\nEnter number 1 to perform square root: ";
cin >> operation;
if (operation==1)
cout << "\n\t" << sqrt(num) << "\n";
else
cout << " \nThe operator is not supported\n\n\n\n\n";
}
else if (op==2)
{
char chart;
float a, b;
cout << "\n\t Enter First Number\n";
cin >> a;
cout << "\n\t Enter Second Number\n";
cin >> b;
cout << "\n\t Enter the binary operator\n";
cin >> chart;
switch (chart)
{
case '+':
cout << "\n\t" << a+b << "\n";
break;
case '-':
cout << "\n\t" << a-b << "\n";
break;
case '*' :
cout << "\n\t" << a*b << "\n";
break;
case '/':
cout << "\n\t" << a/b << "\n";
break;
default:
cout << " \nThe operator is not supported\n\n\n\n\n";
break;
}
}
else
cout << " \nThe operator is not supported\n\n\n\n\n";
return 0;
}

C++: Building a mulitfunctional calculator

I am trying to build a calculator in C++. I'm new to the program and have to do this for a school assignment, so sorry for my ignorance. English is also my second language so excuse me if I don't make much sense.
Let's say I have two integers A and B for which a user has to assign a value to either add, subtract, etc. How would I then be able add a third integer (let's say X) without all three showing up when I run the program? So instead of having to type a value for A, B, AND X, it only asks to type a value for X?
For example 4 + 5 = 9, but the calculator can also square numbers, so how do I get the option of a user just filling in 4 squared = 16, while still keeping the former code that lets me add and subtract two numbers?
Maybe seeing the code would help understand what I mean? Sorry if I'm confusing.
#include <iostream.h>
#include <conio.h>
int main ()
{
cout << "Calculator [v.1.0]" << endl;
cout << "(c) 2021 <Chayenne van der Erf>" << endl << endl;
cout << "Kies een bewerking en druk op Enter:" << endl;
cout << "1. Optellen 2. Aftrekken" << endl;
cout << "3. Vermenigvuldigen 4. Delen" <<endl;
cout << "5. Kwadraat 6. Worteltrekken" <<endl;
cout << "7. Reciproke 8. Logarithme" <<endl;
cout << "0. Exit" << endl << endl;
int Bewerking;
cout << "Bewerking: ";
cin >> Bewerking;
cout << "" << endl;
switch (Bewerking) {
case 1:
cout << "+";
break;
case 2:
cout << "-";
break;
case 3:
cout << "*";
break;
case 4:
cout << "/";
break;
default: "Invalid Number";
}
cout << "" << endl << endl;
double A, B;
cout << "Enter een waarde: ";
cin >> A;
cout << "Enter een waarde: ";
cin >> B;
int antwoord;
if (Bewerking == 1) {antwoord = A + B;}
else if (Bewerking == 2 ) {antwoord = A - B;}
else if (Bewerking == 3) {antwoord = A * B;}
else if (Bewerking == 4) {antwoord = A / B;}
cout << "" << endl;
cout << "= " << antwoord << endl;
getch();
return 0;
}
Make the variables, and the reading, conditional on the operation.
Example outline:
if (operation takes one input)
{
double x;
cin >> x;
Calculate result...
}
else if (operation takes two inputs)
{
double x, y;
cin >> x >> y;
Calculate result...
}
else if (operation takes three inputs)
{
double x, y, z;
cin >> x >> y >> z;
Calculate result...
}
Print result...

C++ First program - Calculator

Hello I just started learning C++ and Im trying to make a calculator, right now having a fue problems that I simply dont know how to fix in C++.
#include <iostream>
using namespace std;
int main() {
int a, b, c, d;
cout << "1. Saskaitiissana(+)" << endl;
cout << "2. atnnemssana(-)" << endl;
cout << "3. daliissana(/)" << endl;
cout << "4. reizinaassana(*)" << endl;
cin >> d;
switch(d){
case 1 :
cout << "ievadiet a un b lai saskaitiitu(+)" << endl;
cin >> a;
cin >> b;
c = a + b;
cout << "The sum of number 1 and number 2 is " << c << "\n" <<endl;
break;
case 2 :
cout << "ievadiet a un b lai atnnemtu(-)" << endl;
cin >> a;
cin >> b;
c = a - b;
cout << c << endl;
break;
case 3 :
cout << "ievadiet a un b lai reizinaatu(*)" << endl;
cin >> a;
cin >> b;
c = a * b;
cout << c << endl;
break;
case 4 :
cout << "ievadiet a un b lai dal'itu(/)" << endl;
cin >> a;
cin >> b;
if(b==0)
{
cout<<"Nulle neder! start over."<<endl;
}
c = a/b;
cout << c << endl;
break;
}
return 0;
}
The things I still have to do.
Find the most easy way for the program to use numbers only. Also when I type in a number it can not be "empty space".
Also how can I make the case after it finish and gives you the result, go back to the begining of start menu? and if I want to exit a program I press esc or 5?
Also with the exit option I was thinking of useing do while "5" is pressed, can that work in c++?
Right now Im most interested on how to check program to use numbers only and have no empty space when adding numbers.
Thank you for your time :)
For ignoring non-numeric input you can this piece of code:
std::cin >> d;
while(std::cin.fail())
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
std::cout << "Bad entry. Enter a NUMBER: ";
std::cin >> d;
}
or in C-style:
while(scanf("%i",&d)!=1)
{
fseek(stdin,0,SEEK_END);
}
You can also put your whole bunch of code in a while statement to re-run the calculator after one operation.
Taking into account the safe input:
//----------------------------------------------------------------------------
#include <iostream>
using namespace std;
//----------------------------------------------------------------------------
void SafeDouble (double &d)
{
while (!(cin >> d))
{ cin.clear();
while (cin.get() != '\n');
cout << "\tIncorrect. Try again\n\t";
}
cin.sync();
}
//----------------------------------------------------------------------------
int main()
{
cout << "The simpliest calculator\n";
double a = 0.,b = 0.;
cout << "\na = ";
SafeDouble (a);
cout << "b = ";
SafeDouble (b);
cout << "\nEnter operation sign: +, -, * or /\n";
char op;
cin >> op;
cin.sync();
switch (op)
{
case '+': cout << a << " + " << b << " = " << a + b;
break;
case '-': cout << a << " - " << b << " = " << a - b;
break;
case '*': cout << a << " - " << b << " = " << a * b;
break;
case '/': if (b == 0.0)
cout << "Division by zero";
else
cout << a << " / " << b << " = " << a / b;
break;
default: cout << "Incorrect operation sign";
}
cin.get();
return 0;
}
//-----------------------------------------------------------------------------

Calculator in C++ with different types and operations to choose

I'm about to create simple calculator in C++. It should allow user to chose type and operations on two typed numbers. So at first, user have to choose number type from list(which shows different types like int, double, short etc.). After that it should allow you to write two numbers of type that you selected before. Then at the end you need to decide what operation would like to do with this numbers (+,-,/,*). My problem is that I don't know how to take those inputted numbers from methods to main() so i could make operations on that.
#include <iostream>
using namespace std;
int integer()
{
int number1;
int number2;
cout << "First number: " << endl;
cin >> number1;
cout << "Second number: " << endl;
cin >> number2;
}
double doubl()
{
double number1;
double number2;
cout << "First number: " << endl;
cin >> number1;
cout << "Second number: " << endl;
cin >> number2;
}
int main()
{
cout << "Type to choose:" << endl;
cout << "1. int" << endl;
cout << "2. double" << endl;
int choosed;
cin >> choosed;
switch(choosed) {
case 1:
integer();
break;
case 2:
doubl();
break;
default:
cout << "Error" << endl;
break;
}
cout << "What operation would like to do on this numbers?" << endl;
cout << "1. +" << endl;
cout << "2. -" << endl;
cout << "3. *" << endl;
cout << "4. /" << endl;
int result;
switch(result){ //at this point i don't know how to invoke those numbers from methods
case 1:
}
cin.get();
}
Thanks!
you can return a std::pair from your functions
std::pair<double,double> doubl()
{
...
return std::make_pair(number1,number2);
}
Then use it
std::pair<double,double> nums = doubl();
double res = nums.first <operation> nums.second;
When you feel comfortable with this I would recommend you to look into using templates to create your reading functions.
Here's one way to do it in C++. Basically, you have to store your answers in a variable in main() and you can use a flag to tell you whether it is a int or a double variable and operation.
#include <iostream>
using namespace std;
template<class T>
class numbers
{
private:
T num1;
T num2;
public:
numbers() : num1(0), num2(0) {}
void setvalues(T n1, T n2) {num1 = n1; num2 = n2;}
T add() {return num1 + num2;}
T subtract() {return num1 - num2;}
T multiply() {return num1 * num2;}
T divide() {return (num2 != 0) ? num1 / num2 : 0;}
};
void integer(numbers<int>& numo)
{
int number1;
int number2;
cout << "First number: " << endl;
cin >> number1;
cout << "Second number: " << endl;
cin >> number2;
numo.setvalues(number1, number2);
}
void doubl(numbers<double>& numo)
{
double number1;
double number2;
cout << "First number: " << endl;
cin >> number1;
cout << "Second number: " << endl;
cin >> number2;
numo.setvalues(number1, number2);
}
int main()
{
cout << "Type to choose:" << endl;
cout << "1. int" << endl;
cout << "2. double" << endl;
int choosed;
cin >> choosed;
numbers<int> num_int;
numbers<double> num_dbl;
int typeOfVal = 0; // 1 for integer, 2 for double
switch(choosed) {
case 1:
integer(num_int);
typeOfVal = 1;
break;
case 2:
doubl(num_dbl);
typeOfVal = 2;
break;
default:
cout << "Error" << endl;
return 1;
}
int typeOfOp = 0;
cout << "What operation would like to do on this numbers?" << endl;
cout << "1. +" << endl;
cout << "2. -" << endl;
cout << "3. *" << endl;
cout << "4. /" << endl;
cin >> typeOfOp;
int resint; //result for int
double resdbl; // result for double
switch(typeOfOp){
case 1:
if (typeOfVal == 1) resint = num_int.add(); else resdbl = num_dbl.add();
break;
case 2:
if (typeOfVal == 1) resint = num_int.subtract(); else resdbl = num_dbl.subtract();
break;
case 3:
if (typeOfVal == 1) resint = num_int.multiply(); else resdbl = num_dbl.multiply();
break;
case 4:
if (typeOfVal == 1) resint = num_int.divide(); else resdbl = num_dbl.divide();
default:
cout << "Error" << endl;
return 1;
}
cout << "The answer:" << endl;
if (typeOfVal == 1) cout << resint << endl;
else cout << resdbl << endl;
cin.get();
return 0;
}
If I were you I would have written the code like this: I think it is more standard than any other above code.
#include<iostream>
#include<string>
using namespace std;
const string EXIT = "-1";
void add(float num1, float num2)
{
cout<<"Result is: "<< num1 + num2 <<endl;
}
void subtract(float num1, float num2)
{
cout<<"Result is: "<< num1 - num2 <<endl;
}
void multiply(float num1, float num2)
{
cout<<"Result is: "<< num1 * num2 <<endl;
}
void divide(float numerator, float denominator)
{
if (denominator != 0)
cout<<"Result is: "<< numerator / denominator <<endl;
else
cout<<"You can not divide by denominator\n";
}
void modulus(float num1, float num2)
{
cout<<"Result is: "<< (int)num1 % (int)num2 <<endl;
}
int main(void)
{
string mathematicalOperation;
float num1, num2;
char operatorSign;
cout << "Please enter an arithmetic expression (-1 to Exit)\n";
cin >> mathematicalOperation;
//search for operator sign and perform calculation
while(mathematicalOperation.compare(EXIT))
{
int getFirstDigitIndex = mathematicalOperation.find_first_of("0123456789");
int operatorSignIndex = mathematicalOperation.find_first_of("+-*/%", getFirstDigitIndex);
if (operatorSignIndex != -1)
{
operatorSign = mathematicalOperation.at(operatorSignIndex);
string firstNumber = mathematicalOperation.substr(0,operatorSignIndex);
string secondNumber = mathematicalOperation.substr(operatorSignIndex + 1);
//convert numbers from string to float
num1 = (float)atof(firstNumber.c_str());
num2 = (float)atof(secondNumber.c_str());
switch(operatorSign)
{
case '+':
add(num1,num2);
break;
case '-':
subtract(num1,num2);
break;
case '*':
multiply(num1,num2);
break;
case '/':
divide(num1,num2);
break;
case '%':
modulus(num1,num2);
break;
}
}
cout<<"Please Enter Another Expression or Enter -1 to Exit:\n";
cin>>mathematicalOperation;
}
cout<<"SEE YOU LATER!\n";
return 0;
}

Switch Statement C++ - error C2046: illegal case, error C2043: illegal break

#include <iostream>
#include <string>
using namespace std;
//void multiply(int b);
int main()
{
float total = 0;
float b = 0;
cout << "Enter number: " << endl;
cin >> b;
char TorD;
cout << "Would you like to times (*), divide (/), add (+) or minus (-) this number?" << endl;
cin >> TorD;
switch (TorD)
case '*' :
{
int c=0;
cout << "by how many?" << endl;
cin >> c;
total = b * c;
cout << b << " * " << c << " = " << total << endl;
}
break;
case '/' :
{
int c=0;
cout << "by how many?" << endl;
cin >> c;
total = b / c;
cout << b << " / " << c << " = " << total << endl;
}
break;
case '+' :
{
int c=0;
cout << "by how many?" << endl;
cin >> c;
total = b + c;
cout << b << " + " << c << " = " << total << endl;
}
break;
case '-' :
{
int c=0;
cout << "by how many?" << endl;
cin >> c;
total = b - c;
cout << b << " - " << c << " = " << total << endl;
}
break;
default:
cout << "You did not correctly enter /, *, +, or - !!" << endl;
//multiply(b);
system("pause");
return 0;
}
You're missing the open brace after the switch (TorD), so the 'break' is outside any statement to break from (i.e. a break has to be inside a loop or switch so it has something to break out of). The switch statement should look like:
switch (TorD) {
case '*': {
// ...
}
break;
case '/': {
// ...
}
break;
// ...and so on.
}
You need braces for your switch:
switch (...)
{ // your forgot this
...
} // and this
You forgot the curly braces around case statements after switch.