#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;
}
Related
How can I make cin accept only a single letter in char datatypes and numbers only in double/int datatypes.
#include <iostream>
using namespace std;
int main (){
char opt;
int num1, num2, sum;
cout << "A. Addition" << endl << "B. Subtraction" << endl;
cout << "Enter option: "; cin >> opt;
//if I put "ab" here, I want to make cin only read the first letter if possible.
switch(opt){
case 'A': case 'a':{
cout << "Enter first number: "; cin >> num1; //accept numbers only
cout << "Enter second number: "; cin >> num2;//accept numbers only
sum = num1+num2;
cout << "The sum is " << sum;
break;
}
}
}
By definition, operator>> reading into a char will read in exactly 1 character, leaving any remaining input in the buffer for subsequent reading. You have to validate the read is successful and the character is what you are expecting before using it.
And likewise, operator>> reading into an int will read in only numbers. You have to validate the read is successful before using the number, and discard any unused input if the read fails to return a valid number.
Try something like this:
#include <iostream>
#include <string>
#include <limits>
using namespace std;
char ReadChar(const char* prompt) {
string s;
do {
cout << prompt << ": ";
if (!(cin >> s)) throw ...;
if (s.length() == 1) break;
//cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Enter a single character" << endl;
}
while (true);
return s[0];
}
char ReadInt(const char* prompt) {
int value;
do {
cout << prompt << ": ";
if (cin >> value) break;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Enter a valid number" << endl;
}
while (true);
return value;
}
int main() {
char opt;
int num1, num2, result;
cout << "A. Addition" << endl << "B. Subtraction" << endl;
opt = ReadChar("Enter option");
switch (opt) {
case 'A': case 'a': {
num1 = ReadInt("Enter first number");
num2 = ReadInt("Enter second number");
result = num1 + num2;
cout << "The sum is " << result << endl;
break;
}
case 'B': case 'b': {
num1 = ReadInt("Enter first number");
num2 = ReadInt("Enter second number");
result = num1 - num2;
cout << "The difference is " << result << endl;
break;
}
default: {
cout << "Invalid option" << endl;
break;
}
}
}
Hey guys haven't been programming for that long so I'm not great and I'm just now getting into error handling and exceptions and thing like that just started learning c++ which is a little different from others I have learned so was wondering if I could get some help here.
I started making a calculator and it went well but I ran into a problem if I input a letter in instead of a number for example if I input a+1 I want it to tell me that i have to enter a number or something like that..I already know ahead of time my code is probably messy so criticism is accepted not going to hurt my feelings. but anyways here is what i have so far
int main()
{
double num1;
double num2;
char operation;
char again;
cout << "Welcome to Brent's Calculator.\n";
cout << "Enter 'Value (operator) Value' ex. 2 + 2" << endl;
cin >> num1 >> operation >> num2;
cout << num1 << " "
<< operation << " "
<< num2 << " = ";
do {
switch (operation) {
case '+':
cout << num1 + num2 << endl;
break;
case '-':
cout << num1 - num2 << endl;
break;
case '*':
case 'x':
case 'X':
cout << num1 * num2 << endl;
break;
case '/':
case '%':
if (num2 == 0) {
cout << "You cant divide by 0" << endl;
}
else {
cout << num1 / num2 << endl;
}
break;
default:
cout << "not understood";
}
cout << "would you like to enter another calculation? (y/n) ";
cin >> again;
cin >> num1 >> operation >> num2;
if (cin.fail()) {
cout << "you need to enter numbers" << endl; //this part added mess with it tomorrow
cin.clear();
cin.ignore(999, '/n');
}
cout << num1 << " "
<< operation << " "
<< num2 << " = ";
} while (again == 'y' || again == 'Y');
//closing bracket of the else for cin.fail
cin.get();
return 0;
}
and of course my if statement with the cin.fail isn't working
Your cin.fail isn't working because of a small typo
Multi-character character constant
cin.ignore(999, '/n');
it should be
cin.ignore(999, '\n');
corrected code
Alright tried one more solution
So the idea is to use continue ..and garble the value of num1 and num2 for invalid value (only present sol for '+').I have used NULL but you can use any other garbled value you want
#include<iostream>
#include <math.h> /* isnan, sqrt */
using namespace std;
int main()
{
double num1;
double num2;
char operation;
char again;
cout << "Welcome to Brent's Calculator.\n";
cout << "Enter 'Value (operator) Value' ex. 2 + 2" << endl;
cin >> num1 >> operation >> num2;
cout << num1 << " "
<< operation << " "
<< num2 << " = ";
do {
switch (operation) {
case '+':
if ((num1 != NULL) && (num2 != NULL ))
cout << num1+ num2 << endl;
break;
case '-':
cout << num1 - num2 << endl;
break;
case '*':
case 'x':
case 'X':
cout << num1 * num2 << endl;
break;
case '/':
case '%':
if (num2 == 0) {
cout << "You cant divide by 0" << endl;
}
else {
cout << num1 / num2 << endl;
}
break;
default:
cout << "not understood";
}
cout << "would you like to enter another calculation? (y/n) ";
cin >> again;
cin >> num1 >> operation >> num2;
if (cin.fail()) {
cout << "you need to enter numbers" << endl; //this part added mess with it tomorrow
cin.clear();
cin.ignore(999, '\n');
num1 = NULL;
num2 = NULL;
continue;
}
cout << num1 << " "
<< operation << " "
<< num2 << " = ";
} while (again == 'y' || again == 'Y');
//closing bracket of the else for cin.fail
cin.get();
return 0;
}
Output After change
Welcome to Brent's Calculator.
Enter 'Value (operator) Value' ex. 2 + 2
44+44
44 + 44 = 88
would you like to enter another calculation? (y/n) y
a+b
you need to enter numbers
would you like to enter another calculation? (y/n) y
4+4.4
4 + 4.4 = 8.4
would you like to enter another calculation? (y/n)
Note: Corner case would be when both entered number is num1 =0 and num2=0
0+0 = 0 (in that case better to use some other flag)
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;
}
Actually i was just trying my hands upon C++ and stopped at this particular problem where instead of program getting closed, it should ask the user whether he/she wants to continue or wants to exit. Now for what i understand, i wrote the do-while code in ending lines but its not working. Please gimme a solution to it. Thanks!!
#include<iostream>
#include<stdio.h>
#include<cstdlib>
#include<string>
using namespace std;
class Cal
{
public:
int Add(int a, int b)
{
int res;
res=(a+b);
cout << "Answer is " << a << "+" << b << "=" << res << endl;
}
int Sub(int a,int b)
{
int res;
res=(a-b);
cout << "Answer is " << a << "-" << b << "=" << res << endl;
}
int Mul(int a,int b)
{
int res;
res=(a*b);
cout << "Answer is " << a << "*" << b << "=" << res << endl;
}
int Div(int a,int b)
{
int res;
res=(a/b);
cout << "Answer is " << a << "/" << b << "=" << res << endl;
}
};
int main()
{
int first, second, res, operation;
cout<<"**********************************"<<endl;
cout<<"******* Simple Calculator ********"<<endl;
cout<<"**********************************"<<endl;
cout<<"Select the Operation: "<<endl;
cout<<"1. Addition"<<endl;
cout<<"2. Subtraction"<<endl;
cout<<"3. Multiplication"<<endl;
cout<<"4. Divison"<<endl;
cout<<"Choosen Operation is: ";
cin>>operation;
cout << "Enter the 1st Number: ";
cin>>first;
cout << "Enter the 2nd Number: ";
cin>>second;
switch(operation){
case 1:
Cal a;
a.Add(first,second);
break;
case 2:
Cal b;
b.Sub(first,second);
break;
case 3:
Cal c;
c.Mul(first,second);
break;
case 4:
Cal d;
d.Div(first,second);
break;
default:
cout<< "Please Enter a Operation";
break;
}
char ans;
do
{
cout<< "Do you want to continue (Y/N)?\n";
cout<< "You must type a 'Y' or an 'N' :";
cin >> ans;
}
while((ans !='Y')&&(ans !='N')&&(ans !='y')&&(ans !='n'));
}
The do while loop does not enclose the body to be repeated, i.e. the calculator part.
The condition in do while does not look correct.
I would try this.
int main() {
char ans = 'N';
do {
// calculator stuff, better to be in a separate function
cout << "Do you want to continue (Y/N)?\n";
cout << "You must type a 'Y' or an 'N' :";
cin >> ans;
} while ((ans == 'Y') || (ans == 'y'));
}
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;
}