0

How do you make a fully functional calculator?

I understand you can make a calculator multiple ways. Most of the instances I see are similar to below... #include <iostream> using namespace std; int main() { float a; float b; cout<<"first number: "; cin>>a; cout<<a<<endl; cout<<"second number: "; cin>>b; cout<<b<<endl<<endl; float sum=a+b; float multiply=a*b; float divide=a/b; float minus=a-b; cout<<"+: "<<sum<<endl; cout<<"x: "<<multiply<<endl; cout<<"/: "<<divide<<endl; cout<<"-: "<<minus<<endl; return 0; } However I would like there to be a prompt like so... "Enter a number" "Enter an operator (+, -, *, /)" "Enter another number" "Answer" I cannot find a way to make the operator an input on its own. Like how you would use a normal calculator. I'm very new to C++. Any help would be greatly appreciated.

30th May 2020, 10:46 PM
Jacob
Jacob - avatar
4 odpowiedzi
+ 1
Hello. You can do this by using the switch case command or the conditional if statement. Create a new input variable as an operator. This variable is a string type. Then, when the user selects the operator, that internal operator of the switch command is checked and the corresponding line is executed. Example: string o; swtich (o) { case "+": a + b; break; case "-": a-b; break; case "×": a × b; break; case "/": a / b; break; }
30th May 2020, 11:36 PM
Saeed ghorbani
Saeed ghorbani - avatar
+ 1
Jacob the easiest and fastest way is infact using switch case and yes you can enter as you pointed out first number operator second number submit https://code.sololearn.com/c9p3ZAD1W8en/?ref=app
30th May 2020, 11:41 PM
BroFar
BroFar - avatar
+ 1
Thank you both. Those are very helpful explanations :)
30th May 2020, 11:43 PM
Jacob
Jacob - avatar
+ 1
Using switch case in your program u can make your code in less lines .
31st May 2020, 12:20 PM
A S Raghuvanshi
A S Raghuvanshi - avatar