PDA

View Full Version : Using functions in C++


Recklein3
10-08-2009, 01:01 AM
currently I've had to write a program that runs functions for each math calculation.

i got the main.cpp (calculator) done

but I'm now having problems understanding how to create functions and have them call for each operation.

any input would be great

here were i stand now:

#include <iostream>

using namespace std;

void main ()
{
float a=0;
float b=0;
int clear=1;
int oper=0;
int loop=0;
char c;

cout << "Welcome to Clifford's Four Function Calculator (v1.803)" <<endl;
cout << endl;

do{

do

{

if (clear==1)
{cout<< "Please enter a number: ";
cin>>a;}
oper=0;
cout<< "Please enter an operator (+,-,*,/) or press X to turn off and C to clear information: ";
do

{
clear=0;
cin>>c;

switch (c)

{

case '+':
case '-':
case '*':
case '/':
clear=0;
break;
case 'C':
case 'c':
clear=1;
cout << "History cleared..." << endl;
break;
case 'X':
case 'x':


cout << "Shutting down..." << endl;
exit (0);
break;
default:


cout << "That is an incorrect operator, please choose one of the following (+,-,*,/) or press X to turn off and C to clear information: ";
cin >>c;
}
}while (oper==1);
}while (clear==1);

cout << "Please enter another number: ";


cin>>b;

if(c=='/'&&b==0)



cout << "Error!: Trying to divide by zero." << endl;


else
{
cout <<a<<""<<c<<""<<b<< "=";

switch (c)

{

case '+':
a=a+b;
break;
case '-':
a=a-b;
break;
case '*':
a=a*b;
break;
case '/':
a=a/b;
break;

}

cout <<a<< endl;

}

}while(loop==0);

}

oracleguy
10-08-2009, 02:52 AM
Please remember to wrap your code with code tags.

Here is how you would do the add function:

#include <iostream>

using namespace std;

int add(int a, int b);

void main ()
{
float a=0;
float b=0;
int clear=1;
int oper=0;
int loop=0;
char c;

cout << "Welcome to Clifford's Four Function Calculator (v1.803)" <<endl;
cout << endl;

do{

do

{

if (clear==1)
{cout<< "Please enter a number: ";
cin>>a;}
oper=0;
cout<< "Please enter an operator (+,-,*,/) or press X to turn off and C to clear information: ";
do

{
clear=0;
cin>>c;

switch (c)

{

case '+':
case '-':
case '*':
case '/':
clear=0;
break;
case 'C':
case 'c':
clear=1;
cout << "History cleared..." << endl;
break;
case 'X':
case 'x':


cout << "Shutting down..." << endl;
exit (0);
break;
default:


cout << "That is an incorrect operator, please choose one of the following (+,-,*,/) or press X to turn off and C to clear information: ";
cin >>c;
}
}while (oper==1);
}while (clear==1);

cout << "Please enter another number: ";


cin>>b;

if(c=='/'&&b==0)



cout << "Error!: Trying to divide by zero." << endl;


else
{
cout <<a<<""<<c<<""<<b<< "=";

switch (c)

{

case '+':
a=add(a, b);
break;
case '-':
a=a-b;
break;
case '*':
a=a*b;
break;
case '/':
a=a/b;
break;

}

cout <<a<< endl;

}

}while(loop==0);

}

int add(int a, int b)
{
return a + b;
}


That is the general idea, so you would then just have additional functions for the other math operations.