I am writing a program in C++ which takes numbers input and it adds substracts divides, and multiplies. In the code when I want the switch case statement to run infinitely until the user presses 5 to exit the program. Please help me. Whenever I am writing the while(true) it is infinitely showing the output.
#include <iostream>
using namespace std;
class SimpleCalculator
{
protected:
private:
int num1, num2;
public:
int add(int a, int b)
{
num1 = a;
num2 = b;
return a + b;
}
int diff(int a, int b)
{
num1 = a;
num2 = b;
return a - b;
}
int quo(int a, int b)
{
num1 = a;
num2 = b;
return a / b;
}
int pro(int a, int b)
{
num1 = a;
num2 = b;
return a * b;
}
};
int main()
{
int n1, n2;
cout << "Enter the value of the number 1: ";
cin >> n1;
cout << "Enter the value of the number 2: ";
cin >> n2;
SimpleCalculator o1;
int input;
cout << "Enter your number: ";
cin >> input;
while (true)
{
switch (input)
{
case 1:
cout << o1.add(n1, n2) << endl;
break;
case 2:
cout << o1.diff(n1, n2) << endl;
break;
case 3:
cout << o1.pro(n1, n2) << endl;
break;
case 4:
cout << o1.quo(n1, n2) << endl;
break;
case 5:
break;
default:
cout << "Invalid entry" << endl;
break;
}
}
return 0;
}
You have two main issues:
The user input requests must be part of the loop since you want them to be repeated at every iteration (i.e. the user needs to make a choice at every iteration).
You forgot to exit the loop in the case 5: statement.
[Optional] Your application is lacking a user menu (the user can't guess what he has to do)
Note: I would advise you to split your code into several functions so that it would be clearer to read and easier to organize.
Note 2: You don't need to use a class for such basic operations, the members are not really needed, you can directly return the result of the operation. My advice would be to define the functions as free functions inside a namespace or as static members of your class if you really want to.
Example:
First let's define the calculation functions:
int add(int a, int b) {return a+b;}
int sub(int a, int b) {return a-b;}
int pro(int a, int b) {return a*b;}
int quo(int a, int b) {return a/b;}
Then we define a function to ask for user inputs:
void ask_user_input(int & lhs, int & rhs)
{
std::cout << "Enter the first operand: ";
std::cin >> lhs;
std::cout << "Enter the second operand: ";
std::cin >> rhs;
}
Finally we define a function to display the user menu:
void display_menu()
{
std::cout << "\n--- Calculator ---\n";
std::cout << "1. Addition\n2. Substraction\n3. Multiplication\n4. Division\n5. Exit\n";
}
Bringing all things together in the main() function, it gives:
int main()
{
bool quit(false);
int choice, lhs, rhs;
while(!quit)
{
display_menu();
std::cin >> choice;
switch(choice)
{
case 1: ask_user_input(lhs, rhs);
std::cout << '\n' << lhs << " + " << rhs << " = " << add(lhs, rhs) << '\n';
break;
case 2: ask_user_input(lhs, rhs);
std::cout << '\n' << lhs << " - " << rhs << " = " << sub(lhs, rhs) << '\n';
break;
case 3: ask_user_input(lhs, rhs);
std::cout << '\n' << lhs << " * " << rhs << " = " << pro(lhs, rhs) << '\n';
break;
case 4: ask_user_input(lhs, rhs);
std::cout << '\n' << lhs << " / " << rhs << " = " << quo(lhs, rhs) << '\n';
break;
case 5: quit = true;
break;
default: std::cout << "Invalid choice, try again !\n";
break;
}
}
return 0;
}
Live example
Related
the problem that in the main body the getwhattheywant function is executing twice what I want is this
getwhattheywant execute then the user entered one then if the user entered one do the summation operation but what is happening with me that it's reasking the user to enter a number.
#include <iostream>
using namespace std;
double dothesum(int x, int y)
{
int sum = x + y;
return sum;
};
int getwhatheywant()
{
int choice;
cout << "1- for sum " << endl;
cout << "2- for quit ";
cin >> choice;
return choice;
}
void the_sum()
{
int x, y;
cout << " enter the first number " << endl;
cin >> x;
cout << " enter the second number " << endl;
cin >> y;
cout << " the sum of the two number is " << dothesum(x, y) << endl;
}
int main()
{
int;
while (getwhatheywant() != 2) {
if (getwhatheywant() == 1) {
the_sum();
}
}
return 0;
}
Change your main():
int main()
{
int whatTheyWant;
while ( (whatTheyWant = getwhatheywant()) != 2) {
if (whatTheyWant) == 1) {
the_sum();
}
}
return 0;
}
This stores the value from a single call to getwhattheywant() so you can first see if they're asking to quit, and if not, you can see what else they might want. Now, I'd write it slightly differently:
bool working = true;
while(working) {
int choice = getWhatTheyWant();
switch(choice) {
case 1: the_sum(); break;
case 2: working = false; break;
}
}
I am a new contributor and here I am trying to make a simple calculator but having errors in my code. When I compile the code I get:
Error: C:\Users\IJLAL\Documents\collect2.exe [Error] ld returned 1 exit status while compiling
In case it could help, here is the screen shot of error when I pressed compile button or F11 in Dev C++:
Here is my code:
#include<iostream>
using namespace std;
void fun(float a, float b);
int main()
{
float a, b, sum, sub, mul, divide, mod;
char op;
//operands and operators are enterd by the user
cout<<"Enter any two operands with operator=";
cin>>a>>op>>b;
fun(a, b);
return 0;
}
void op(float a, float b)
{
if(a+b)
{
float sum=a+b;
cout<<"\nAddition of two numbers is="<<sum;
}
else if(a-b)
{
float sub=a-b;
cout<<"\nSubtraction of two numbers is="<<sub;
}
else if(a*b)
{
float mul=a*b;
cout<<"\nMultiplication of two numbers is="<<mul;
}
else if(a/b)
{
float divide=a/b;
cout<<"\nDivision of two number is="<<divide;
}
else
{
cout<<"\nInvalid operator.......";
}
}
Please tell me the solution of this problem, so that I can compile the code successfully. If there is any better solution to make a simple calculator on beginner level please mention it in answer.
You're not so far from a result. The problem is that you have not defined the function fun(). Furthermore, in the function op() that you have defined, you do not use the operator of the input.
So first thing to do is to change the signature of the function:
void fun(char op, float a, float b);
Then you need to invoke your function in main(), passing also the operation that was requested by the user:
fun(op, a, b);
Finally you need to change all your if to check if op is the matching operator:
void fun(char op, float a, float b)
{
if(op=='+')
{
...
}
else if(op=='-')
{
...
You should then get the expected result.
Online demo
Aditional infos
if (a+b) just calculates the expression using the two values of the user, and if it's non zero, it's considered as true.
once you got this program to work, you can look for the switch statement
You can use additional functions to make a better calculator. You can use this code. Hope this code will be helpful for you.
The header <iomanip> is part of the Input/output library of the C++ Standard Library and <math.h> is used when we perform mathematical operations.
#include<iostream>
#include<conio.h>
#include<math.h>
#include<iomanip>
char op;
using namespace std;
void sum()
{
int sum = 0;
int n;
int numberitems;
cout << "Enter number of items: \n";
cin >> numberitems;
for(int i=0;i<numberitems;i++)
{
cout<< "Enter number "<<i<<":\n\n" ;
cin>>n;
sum+=n;
}
cout<<"sum is: "<< sum<<endl<<endl;
}
void diff()
{
int diff;
int n1,n2;
cout<<"enter two numbers to find their difference:\n\n";
cout<<"enter first number:";
cin>>n1;
cout<<"\nenter second number:";
cin>>n2;
diff=n1-n2;
cout<<"\ndifference is:"<<diff<<endl<<endl;
}
void pro()
{
int pro=1;
int n;
int numberitems;
cout<<"enter number of items:\n";
cin>>numberitems;
for(int i=0;i<=numberitems;i++)
{
cout<<"\nenter item "<<i<<":";
cin>>n;
pro*=n;
}
cout<<"product is:"<<pro<<endl<<endl;
}
void div()
{
int div;
int n1;
int n2;
cout<<"enter 2 numbers to find their quotient\n\n";
cout<<"enter numerator:";
cin>>n1;
cout<<"\nenter denominator:";
cin>>n2;
div=n1/n2;
cout<<"\nquotient is:"<<div<<endl<<endl;
}
void power()
{
long int p;
int res=1,n;
cout<<"enter number:";
cin>>n;
cout<<"\nenter power:";
cin>>p;
for(int i=1;i<=p;i++)
{
res=n*res;
}
cout<<n<<"\n power "<<p<<" is :"<<res<<endl;
}
void sq()
{
float s;
int n;
cout<<"enter number to find its square root:";
cin>>n;
s=sqrt(n);
cout<<"\nsquare root of "<<n<<" is :"<<s<<endl;
}
void fact()
{
long int f=1;
int c=1,n;
cout<<"enter number to find its factorial:";
cin>>n;
while(c<=n)
{
f=f*c;
c+=1;
}
cout<<"\nfactorial of "<<n<<" is :"<<f<<endl;
}
void expo()
{
long double res=1,p;
double e=2.718281828;
cout<<"enter power of exponential function:";
cin>>p;
for(int i=1;i<=p;i++)
{
res=e*res;
}
cout<<" e^ "<<p<<" is :"<<res<<endl;
}
int main()
{
system("cls");
do
{
system("pause");
system("cls");
cout<<"***which operation you want to perform***\n";
cout<<"press 0 for exit\n";
cout<<"press 1 for addition \n";
cout<<"press 2 for subtraction\n";
cout<<"press 3 for multiplication\n";
cout<<"press 4 for division\n";
cout<<"press 5 for power calculation\n";
cout<<"press 6 for square root \n";
cout<<"press 7 for factorial calculation\n";
cout<<"press 8 for exponential calculation\n";
cout<<"press option:";
cin>>op;
switch(op)
{
case '1':
sum();
break;
case '2':
diff();
break;
case '3':
pro();
break;
case '4':
div();
break;
case '5':
power();
break;
case '6':
sq();
break;
case '7':
fact();
break;
case '8':
expo();
break;
case '0':
exit(0);
default:
cout<<"invalid input" ;
system("cls");
}
}
while(op!='0');
getch();
}
Hey I'm still a newbie on c++ but hope this would help, I used while loop to loop the calculator but I don't have a good error handler for example when users try to input a letter instead of numbers.
#include <iostream>
#include <cmath>
using namespace std;
int result (int a, int b, char op);
int main()
{
char optr, choice;
int nr1, nr2;
while (true){
cout << "Enter first number: ";
cin >> nr1;
cout << "Enter an operator (+ - / * %) : ";
cin >> optr;
cout << "Enter second number: ";
cin >> nr2;
result (nr1, nr2, optr);
cout<<"Would you like to perform other calculation?(Y/N): ";
cin >> choice;
if (choice =='N'||choice =='n'){
break;
}
}
}
int result (int a, int b, char op)
{
int result;
if (op == '+'){
result = a + b;
cout << "Result to " << a << " + " << b << " = " << result << endl;
} else if (op == '-'){
result = a - b;
cout << "Result to " << a << " + " << b << " = " << result << endl;
} else if (op == '*'){
result = a * b;
cout << "Result to " << a << " * " << b << " = " << result << endl;
} else if (op == '/'){
result = a / b;
a / b;
cout << "Result to " << a << " / " << b << " = " << result << endl;
} else if (op == '%'){
result = a % b;
cout << "Remainder to " << a << " % " << b << " = " << result << endl;
} else {
cout <<"Error 404: " << a << op << b <<" Wrong input format. Program terminated." << endl;
// i still dont know how to properly use error handling
}
}
I won't criticize your solution as I have a better solution as you mentioned "please mention a better solution in answer"
Here's my solution with comments to make you understand what each statement does.
#include <iostream>
using namespace std;
// I am going to show How to Design a program
// We have to break down our progress a bit by bit
// and do the progress of one thing with function
// For calculator we have to take input from user keyboard twice,
// And an opperator from user
int userInput() // this requires to get input from user keyboard
{
cout << "Enter a number: ";
int no{};
cin >> no;
return no;
}
char userOpr() // Using type char to store the ASCI Opperator means requires char to store +,*,/,-
{
cout << "Enter opperator: ";
char opr{};
cin >> opr;
return opr;
}
int calculate(int input1, char opper, int input2)
{
if (opper == '+')
{
return input1 + input2;
}
else if (opper == '-')
{
return input1 - input2;
}
else if (opper == '*')
{
return input1 * input2;
}
else if (opper == '/')
{
return input1 / input2;
}
return 0;
}
int main()
{
// get the first no. from user
// getUserInput();
// get the math oppperator from the user
// getMathOpperator();
// get the second no. from the user
// getUserInput();
// calculate the values
// calculateResults();
// print out the results
// printResults();
cout << "Hello This is a simple calculator program Designed by Shankhui!\n\n";
while (true)
{
int input1{ userInput() };
int input2{ userInput() };
char opper{ userOpr() }; // Using type char to store the ASCI Opperator means requires char to store +,*,/,-
cout << input1 << " " << opper << " " << input2 << " = " << calculate(input1, opper, input2) << '\n' << '\n';
}
return 0;
}
Just copy this code and modify however you want to.
#include <iostream>
int main() {
int math_ques_1, math_ques_2;
std::cout << "What is the base of the question?" << std::endl;
std::cin >> math_ques_1;
std::cout << "What do you want to add to the base?" << std::endl;
std::cin >> math_ques_2;
std::cout << "The answer is " << math_ques_1 + math_ques_2 << "." << std::endl; }
For example lets say I have this simple code:
using namespace std;
char re = 'y';
void mult(int one, int two)
{
int mult = 1;
mult = one * two;
cout << mult << endl;
}
void add(int one, int two)
{
int add = 0;
add = one + two;
cout << add << endl;
}
void rep(int one, int two)
{
}
void ask()
{
int re;
cout << "do you want return to the menu? (1/2)" << endl;
cin >> re;
}
int main()
{
char re;
int one;
int two;
cout << "enter the number one:" << endl;
cin >> one;
cout << "enter the number two:" << endl;
cin >> two;
cout << endl;
cout << "Multiply - 1" << endl;
cout << "Add - 2" << endl;
cout << "Reprint - 3" << endl;
cout << endl;
int menu;
if (re == 'y')
{
cout << "select the function ";
cin >> menu;
switch (menu)
{
case 1:
mult(one, two);
ask();
break;
case 2:
add(one, two);
ask();
break;
case 3:
rep(one, two);
break;
default:
cout << "no such thing" << endl;
break;
}
}
else if (re != 'y')
{
}
return 0;
}
I need a way function rep to print out the answer of previously called functions.
For example if function mult was called it should print mult answer, IF mult and add were called then it should print mult and add function answers, if only add then only add.
I was thinking about creating a zero array and changing it whether function one or two was called out, and then somehow call the answers out. But no idea how to do it.
You could use a global variable.
int last_result = 0;
void mult(int a, int b)
{
last_result = a * b;
std::cout << last_result << std::endl;
}
void add(int a, int b)
{
last_result = a + b;
std::cout << last_result << std::endl;
}
void rep()
{
std::cout << "Last result: " << last_result << std::endl;
}
You could also have the mult and add functions return a result and store the result in main (and pass it to the rep function).
You could pass the last_result variable by reference to the add and mult functions.
I am having this problem with my calculator I made. See, when I type in a calculation it always adds a 0 to the end. I don't know how to fix this do you have any ideas?
Here's the code:
#include <iostream>
using namespace std;
void Input(float &x, float &y);
float a = 1.0, b = 1.0, result;
char op;
int main() {
cout << "Welcome to Foxy's calculator" << endl;
cout << "----------------------------" << endl;
cout << "Please input a calculation operation (eg. 1+1): ";
cin >> a >> op >> b;
Input(a, b);
cout << result << endl;
system("pause");
return 0;
}
void Input (float &x, float &y) {
a = x;
b = y;
switch (op)
{
case '+':
cout << x + y;
break;
case '-':
cout << x - y;
break;
case '*':
cout << x*y;
break;
case '/':
cout << x / y;
break;
default:
cout << "Error! Operator is not correct" << endl;
cout << "Please input your calculation with a proper operator: ";
cin >> a >> op >> b;
}
}
result is a global static variable that gets zero - initialized and is never changed. So cout << result << endl; will always print "0". To fix this you should make a, b, result and op local to main (global variables are bad), pass a, b andop to calculating function and store returned calculation result in result. It will look something like this:
float result = Input(a, b, op);
cout << result << endl;
You call cout << result << endl; in the caller. and result is always 0. This is because it is never explicitly set to anything and the C++ compiler kindly zero-initialises it since it's at global scope.
In such instances, your line by line debugger is your best friend. The fact that you've mashed up your 1) input, 2) calculation, and 3) output stages is not helping: ideally they should all be separate parts of your program.
Remove cout << result << endl;
I have a 3 file program, basically teaching myself c++. I have an issue. I made a switch to use the math function. I need and put it in a variable, but for some reason I get a zero as a result.
Also another issue, when I select 4 (divide) it crashes... Is there a reason?
Main file:
#include <iostream>
#include "math.h"
#include <string>
using namespace std;
int opersel;
int c;
int a;
int b;
string test;
int main(){
cout << "Welcome to Math-matrix v.34"<< endl;
cout << "Shall we begin?" <<endl;
//ASK USER IF THEY ARE READY TO BEGIN
string answer;
cin >> answer;
if(answer == "yes" || answer == "YES" || answer == "Yes")
{
cout << "excellent lets begin..." << endl;
cout << "please select a operator..." << endl << endl;
cout << "(1) + " << endl;
cout << "(2) - " << endl;
cout << "(3) * " << endl;
cout << "(4) / " << endl;
cin >> opersel;
switch(opersel){
case 1:
c = add(a,b);
break;
case 2:
c = sub(a,b);
break;
case 3:
c = multi(a,b);
break;
case 4:
c = divide(a,b);
break;
default:
cout << "error... retry" << endl;
}// end retry
cout << "alright, how please select first digit?" << endl;
cin >> a;
cout << "excellent... and your second?" << endl;
cin >> b;
cout << c;
cin >> test;
}else if (answer == "no" || answer == "NO" || answer == "No"){
}//GAME ENDS
}// end of int main
Here is my math.h file
#ifndef MATH_H
#define MATH_H
int add(int a, int b);
int sub(int a, int b);
int multi(int a, int b);
int divide(int a, int b);
#endif
Here is my math.cpp:
int add(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
int multi(int a, int b)
{
return a * b;
}
int divide(int a, int b)
{
return a / b;
}
}// end of int main
You're calling your functions with a and b before you get the data from the user. Try saving the math function that they selected when they enter it, and move your switch to after you have asked them for a and b.
#include <iostream>
#include "math.h"
#include <string>
using namespace std;
int opersel;
int c;
int a;
int b;
string test;
int main(){
cout << "Welcome to Math-matrix v.34"<< endl;
cout << "Shall we begin?" <<endl;
//ASK USER IF THEY ARE READY TO BEGIN
string answer;
cin >> answer;
if(answer == "yes" || answer == "YES" || answer == "Yes")
{
cout << "excellent lets begin..." << endl;
cout << "please select a operator..." << endl << endl;
cout << "(1) + " << endl;
cout << "(2) - " << endl;
cout << "(3) * " << endl;
cout << "(4) / " << endl;
cin >> opersel;
cout << "alright, how please select first digit?" << endl;
cin >> a;
cout << "excellent... and your second?" << endl;
cin >> b;
switch(opersel){
case 1:
c = add(a,b);
break;
case 2:
c = sub(a,b);
break;
case 3:
c = multi(a,b);
break;
case 4:
c = divide(a,b);
break;
default:
cout << "error... retry" << endl;
}// end retry
cout << c;
cin >> test;
}else if (answer == "no" || answer == "NO" || answer == "No"){
}//GAME ENDS
}// end of int main
It looks like you are calling your math functions (inside the switch statement) before you populate your input variables a and b. Move the cin calls to above the switch and your problems should go away.
The crash is most likely caused when you call divide(a,b) because a and b are both 0. In that case you divide by zero and the system won't be happy about that.
You are doing your calculations before you even read a and b into their variables. The cin >> statements come after your switch statements.
This is a function call:
c = add(a,b);
It assigns to c the return value of calling add with parameters a and b. At the time you're calling this function, a and b have not been initialized. Put your switch after this line:
cin >> b;
and things should work as you expect.
You need to move these:
cout << "alright, how please select first digit?" << endl;
cin >> a;
cout << "excellent... and your second?" << endl;
cin >> b;
to before the switch. If you are thinking that a function like this:
int f( int x, int y ) {
return x + y;
}
somehow returns the expression "x + y" which can be evaluated later, it doesn't. It returns the result of evaluating x + y at that point in the program. There are languages that can return an expression, but C++ isn't one of them.
c = add(a,b); within your switch statement doesn't store the function, it calls the function, passing it a and b as arguments. This is the same for all your other cases. But at that point in the program, you haven't actually set a and b yet. They are uninitialized, so they can be anything. Including 0, which would cause problems when you divide. Edit: Actually, I just realized they are globals. So they should be initialized to zero for you, which would guarantee that the divide option will fail. If a and b were local to within main, they would be uninitialized, and you could make no assumptions as to what they initially hold.
It is possible to store an address to a pointer, but its a relatively advanced topic, and I would recommend you wait until you have a better grasp on the basics before getting into it. For now, what you're better off doing is getting all your input from the user, and then processing it all at once. In pseudo-code, your loop would look something like this:
Get Operator
If Operator < 0 or Operator > 4 Then "Error"
Get A
Get B
Switch Operator
1: Result = Add(A, B)
2: Result = Subtract(A, B)
3: Result = Multiply(A, B)
4: Result = Divide(A, B)
Output result
Note that there are a lot of "gotchas" when it comes to user input. For instance, when you ask the user to input the value for a, what if they enter "Five"? At the very least, you'll want to check the status of cin after any input; this will tell you if it got any valid data from the user or not. cin.good() should tell you if the previous operation was successful, and if not you can quit, or try again, or whatever you like.
Here's an idea (using function objects or functors):
#include <iostream>
using std::cin;
using std::cout;
struct Math_Operation
{
virtual int operator()(int a, int b) = 0;
};
struct Math_Add : Math_Operation
{
int operator()(int a, int b)
{ return a + b;}
};
struct Math_Sub : Math_Operation
{
int operator()(int a, int b)
{ return a - b;}
};
struct Math_Mul : Math_Operation
{
int operator()(int a, int b)
{ return a * b;}
};
struct Math_Div : Math_Operation
{
int operator()(int a, int b)
{ return a / b;}
};
int main(void)
{
cout << "Enter operation (+, -, *, /): ";
cout.flush();
char operation;
Math_Operation * p_math_opr = NULL;
cin >> operation;
switch (operation)
{
case '+':
p_math_opr = new Math_Add;
break;
case '-':
p_math_opr = new Math_Sub;
break;
case '*':
p_math_opr = new Math_Mul;
break;
case '/':
p_math_opr = new Math_Div;
break;
default:
p_math_opr = NULL;
}
// ...Input numbers into A & B...
int A = 5;
int B = 8;
// Perform calculation with A & B
int Result = 0;
if (p_math_opr)
{
Result = (*p_math_opr)(A, B);
delete p_math_opr;
}
cout << "Result is: " << Result << "\n";
return 0;
}
The functor approach allows you to save an operation. Using pointers to base class allows you to execute the functor without knowing which operation is "in-use".
Edit:
1. Added int to function definitions in child classes.
2. Corrected execution syntax of functor.
3. Added deletion of functor.
You're calling the math functions in your switch statement before you've read a and b from the user, so it's getting called with whatever happens to be in those variables at the time. You need to move the switch after reading a and b from the user, before outputting c
This might be going overboard, but rather than using a switch to accomplish that, you can use an array of function pointers:
typedef int (*math_function)(int, int);
math_function fns[] = {NULL, add, sub, multi, divide};
cin >> opersel;
if(opersel <= 4)
cout << fns[opersel](a, b);
else
cout << "You fail :(";