Creating a C++ Calculator Program for Basic Mathematical Operations

Verified

Added on  2022/10/02

|5
|460
|16
Homework Assignment
AI Summary
This assignment presents a C++ program designed to function as a basic calculator. The program includes functionalities for addition, subtraction, multiplication, and division. It prompts the user to input two numbers and select an operation. The program uses a 'switch' statement to handle the different operations based on user input. The program includes error handling to prevent division by zero and provides a user-friendly interface. The code is well-structured and easy to understand, making it a useful example for learning basic programming concepts. The program includes a loop to allow the user to perform multiple calculations until they choose to exit. This solution is available on Desklib, a platform offering various AI-based study tools for students.
Document Page
Source Code
#include<iostream>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
#include<iomanip>
char ch;
using namespace std;
void add(float x,float y)
{
float z;
z=x+y;
cout<<"Sum is: "<<z<<endl;
}
void sub(float x,float y)
{
float z;
z=x-y;
cout<<"\nDifference is:"<<z<<endl;
}
void mul(float x,float y)
{
float z;
z=x*y;
cout<<"Product is:"<<z<<endl;
}
void div(float x,float y)
{
float z;
if(y==0)
{
cout<<"Cannot be divided by 0"<<endl;
}
else
{
z=x/y;
cout<<"\nQuotient is:"<<z<<endl;
}
}
int main()
{
float a,b;
tabler-icon-diamond-filled.svg

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
do
{
cout<<"Basic Mathematical Operations \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 exit\n";
cout<<"Enter your choice:";
cin>>ch;
switch(ch)
{
case '1':
cout<<"Enter two numbers \n";
cin>> a>>b;
add(a,b);
break;
case '2':
cout<<"Enter two numbers \n";
cin>> a>>b;
sub(a,b);
break;
case '3':
cout<<"Enter two numbers \n";
cin>> a>>b;
mul(a,b);
break;
case '4':
cout<<"Enter two numbers \n";
cin>> a>>b;
div(a,b);
break;
case '5':
exit(0);
default:
cout<<"Invalid input..select a valid input" ;
system("cls");
}
}
while(ch!='0');
getch();
}
Document Page
Output
Addition
Subtraction
Document Page
Multiplication
Division
tabler-icon-diamond-filled.svg

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
Exit
chevron_up_icon
1 out of 5
circle_padding
hide_on_mobile
zoom_out_icon
[object Object]