I am a beginner to C++ and pretty much programming altogether (besides a little html and css).
I have decided to start my first project for C++.
A friend recommended me trying to make a simple calculator so here is my first shot. Any pointers would be great too! Not sure exactly what I am missing, if anything, but the error I am receiving is:
1>------ Build started: Project: CalculatorFinal, Configuration: Debug Win32 ------
1> CalculatorFinal.cpp
1>c:\users\ramee\documents\visual studio 2010\projects\calculatorfinal
\calculatorfinal\calculatorfinal.cpp(32): warning C4102: 'calc' : unreferenced label
1> CalculatorFinal.vcxproj -> c:\users\ramee\documents\visual studio 2010
\Projects\CalculatorFinal\Debug\CalculatorFinal.exe
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
my code is below (apologize if its not formatted correctly on here. This is my first post :D
// CalculatorFinal.cpp : Defines the entry point for the console application.
//
#include "stdafx.h" // Including header
#include <iostream> // Including ioStream
using namespace std; // Namespace
void calc (double x, double y);
double result;
double n1,n2; // Declaring Variables
char q,operation;
int main()
{
cout<<"Welcome to My Calculator" <<endl; // Outputs welcome message
cout<<""<<endl; // Blank Space
cout<<"INSTRUCTIONS: Input a mathmatical equation" <<endl; // Outputs instruction
cout<<" EX: 2 + 2" <<endl; // Outputs instruction
cout<<""<<endl; // Blank Space
cout<<"Operators:"<<endl; // Outputs operation header
cout<<"For Addition, select '+'"<<endl // Outputs ADD instruction
cout<<"For Subtraction, select '-'"<<endl; // Outputs SUB instruction
cout<<"For Multiplication, select '*'"<<endl; // Outputs MUL instruction
cout<<"For Division, select '/'"<<endl; // Outputs DIV instruction
cout<<""<<endl; // Blank Space
cout<<"To clear, select 'c'"<<endl; // Outputs clear instruction
cout<<"To quit, select 'q'"<<endl; // Outputs QUIT instruction
cout<<""<<endl; // Blank Space
cout<<"Input a mathmatical equation"<<endl; // Input instructions
cin>>n1>>operation>>n2;
calc:(n1,n2);
cout<<"The answer is:"<<result<<endl;
std::cin>>q; // Input "q" to "quit"
return 0;}
void calc(double x, double y) // Operator function
{ x=n1;
y=n2;
switch(operation) // Operator swtich statement
{case '+':
result = x + y;
break;
case '-':
result = x - y;
break;
case '*':
result = x * y;
break;
case '/':
result = x / y;
break;
default:
cout<<"Improper equation. Please input a valid mathmatical equation"<<endl;
cin>>n1>>operation>>n2;
calc (n1,n2);
}
}
Here is a calculator program I wrote based off of yours which is much nicer:
#include <iostream>
using namespace std;
//Function prototype
int solve(int, int, char);
int main()
{
//Declare variables
int solution, num1, num2;
char oper;
//Output
cout << "Calculator\n----------\n" << endl;
cout << "Syntax:\n" << endl;
cout << "1 + 3\n" << endl;
cout << "Operators: +, -, *, /\n" << endl;
cout << "Equation: ";
//Input
cin >> num1 >> oper >> num2;
//Solve and output
solution = solve(num1, num2, oper);
cout << "Answer: " << solution << endl;
//Pause [until enter key] and exit
cin.ignore(); //Enter key from last cin may be passed, ignore it.
cin.get();
return 0;
}
int solve(int num1, int num2, char oper)
{
//Switch oper
switch(oper)
{
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num1 / num2;
default:
cout << "\nIncorrect operation! Try again: ";
cin >> num1 >> oper >> num2;
solve(num1, num2, oper);
}
}
Here are some things to watch out for, from your last program:
1) Function prototypes do not have function names [i.e void func(int)]
2) Use return values [i.e. return result;]
3) Make sure you have semi-colons.
.
.
.
.
[OLD POST:
cout<<"For Addition, select '+'"<;* // Outputs ADD instruction
[No ending semi-colon]
FYI:
std::cin>>q; // Input "q" to "quit"
std:: not required here. (using namespace std;)
(remove colon in calc:(n1,n2);)
--
Your program will work now.]
I wouldn't call this as a C++ program. It is a mistake which almost all amateur C++ programmers make. I would call this as a C style of writing C++ programs. Please don't get me wrong but you need to start thinking in object oriented way so that you can leverage the true power of C++.
I would recommend you to make a C++ class called calculator and think on the design of the class for a bit before starting to code. I would keep methods such as Add, Subtract, Divide and so on as public and other methods as private. This would also give you a chance to enhance the calculator class in future like say adding memory support to it so that it remembers the last operation or result. Start thinking in object oriented way, in order to avoid spaghetti code which is difficult to manage later.
I've commented that I have changed from your original source code.
and I've checked this code is working on GCC ( G++ ) compiler
Good luck!
#include "stdafx.h"
#include <iostream>
using namespace std;
void calc (double _x, double _y); // CHANGED
double result;
double n1,n2;
double x,y; // CHANGED
char q,operation;
int main()
{
cout<<"Welcome to My Calculator" <<endl;
cout<<""<<endl;
cout<<"INSTRUCTIONS: Input a mathmatical equation" <<endl;
cout<<" EX: 2 + 2" <<endl;
cout<<""<<endl;
cout<<"Operators:"<<endl;
cout<<"For Addition, select '+'"<<endl;
cout<<"For Subtraction, select '-'"<<endl;
cout<<"For Multiplication, select '*'"<<endl;
cout<<"For Division, select '/'"<<endl;
cout<<""<<endl;
cout<<"To clear, select 'c'"<<endl;
cout<<"To quit, select 'q'"<<endl;
cout<<""<<endl;
cout<<"Input a mathmatical equation"<<endl;
cin>>n1>>operation>>n2;
calc(n1,n2); // CHANGED
cout<<"The answer is:"<<result<<endl;
std::cin>>q;
return 0;
}
void calc(double _x, double _y) // CHANGED
{
x=_x; // CHANGED
y=_y; // CHANGED
switch(operation)
{case '+':
result = x + y;
break;
case '-':
result = x - y;
break;
case '*':
result = x * y;
break;
case '/':
result = x / y;
break;
default:
cout<<"Improper equation. Please input a valid mathmatical equation"<<endl;
cin>>x>>operation>>y; // CHANGED
calc (x,y); // CHANGED
}
}
This is my code,it too long but support more operators
#include "stdafx.h"
#include"iostream"
#include"math.h"
#include"iomanip"
#include <string>
#include <sstream>
using namespace std;
double calc(string mystring);
double calc2(string mystring);
double factoriel(double number);
double root(double num1,double num2);
double dowork(int a,int b,string c);
int main(){
cout<<"***************************************************\n";
cout<<"* *\n";
cout<<"* calculator *\n";
cout<<"***************************************************\n\n\n";
string inpstring;
cin >> inpstring;
int length_string=inpstring.length();
double result;
if(abs(calc(inpstring))>abs(calc2(inpstring))){
result=calc(inpstring);
}
else if(abs(calc(inpstring))<=abs(calc2(inpstring))){
result=calc2(inpstring);
}
double s;
s=3.14;
cout<<"\n"<<"\tresult : "<<result<<endl;
system("pause");
}
double calc(string mystring){
int a=0;//just for switchings
int numberofop=0;
int length_string=mystring.length();
string ops;
string myop;
double param1=0;
double param2=0;
double result=0;
string first_inp;
string second_inp;
ops="+-*/^%!R";
int length_ops=ops.length();
for (int i=0;i<=length_string-1;i++){
if (i==0){
if(mystring.substr (0,1)=="-"){
continue;
}
}
for (int j=0;j<=length_ops-1;j++){
if (!(mystring.substr (i,1).compare(ops.substr(j,1)))){
numberofop++;
if (numberofop==1){
myop=ops.substr(j,1);
first_inp = mystring.substr (0,i);
second_inp = mystring.substr (i+1,length_string-1);
stringstream(first_inp) >> param1;
stringstream(second_inp) >> param2;
if (myop=="+"){
a=1;
}
else if(myop=="-"){
a=2;
}
else if(myop=="*"){
a=3;
}
else if(myop=="/"){
a=4;
}
else if(myop=="^"){
a=5;
}
else if(myop=="%"){
a=6;
}
else if(myop=="!"){
a=7;
}
else if(myop=="R"){
a=8;
}
}
}
}
}
switch (a){
case 1:
result=param1+param2;
break;
case 2:
result=param1-param2;
break;
case 3:
result=param1*param2;
break;
case 4:
result=param1/param2;
break;
case 5:
result= pow(param1,param2);
break;
case 6:
result= int(param1)% int(param2);
break;
case 7:
result= factoriel(param1);
break;
case 8:
result= root(param1,param2);
break;
}
return result;
}
double factoriel(double a){
cout<<"enter number \n";
double i=a;
double d=1;
while(i>1){
d=d*i;
i--;
}
return d;
}
double root(double num1,double num2){
double result;
double reverce;
reverce=1/num2;
result=pow(num1,reverce);
return result;
}
double calc2(string mystring){
int a=0;//just for switchings
int numberofop=0;
int length_string=mystring.length();
double pi=3.1415;
double teta;
string ops;
string myop;
double param1=0;
double param2=0;
double result=0;
string first_inp;
string second_inp;
ops="logsincostancot";
int length_ops=ops.length();
for (int i=0;i<=length_string-1;i++){
if (i==0){
if(mystring.substr (0,1)=="-"){
continue;
}
}
for (int j=0;j<=length_ops-1;j++){
if (!(mystring.substr (i,3).compare(ops.substr(j,3)))){
numberofop++;
if (numberofop==1){
myop=ops.substr(j,3);
second_inp = mystring.substr (i+3,length_string-1);
stringstream(second_inp) >> param2;
if (myop=="log"){
a=1;
}
else if(myop=="sin"){
a=2;
}
else if(myop=="cos"){
a=3;
}
else if(myop=="tan"){
a=4;
}
else if(myop=="cot"){
a=5;
}
}
}
}
}
switch (a){
case 1:
result=log(param2);
break;
case 2:
teta=(double(param2)*pi)/180;
result=sin(teta);
break;
case 3:
teta=(double(param2)*pi)/180;
result=cos(teta);
break;
case 4:
teta=(double(param2)*pi)/180;
result=tanf(teta);
break;
case 5:
teta=(double(param2)*pi)/180;
result=1/tanf(teta);
break;
}
return result;
}
double dowork(int a,int b,string c){
string cut;
cut=c.substr(a,b);
double result;
result=calc(cut);
cout<<"\nresult is "<<result;
return result;
}
I had coded this simple calculator using c++ so that we can add, subtract, divide or multiple as many numbers as we want. example: 2+3+4-2= and then you will get your answer.
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
char c;
while(true){
cout << "To solve your math problem you can use this syntex: number(+, -, / or *)number=" << endl;
cout << "you can use as many number as you want." << endl << endl;
int n, ans;
char oper;
cin >> n;
ans = n;
cin >> oper;
while(oper!='='){
cin >> n;
if(oper=='+'){
ans = ans + n;
}
if(oper=='-'){
ans = ans - n;
}
if(oper=='/'){
ans = ans/n;
}
if(oper=='*'){
ans = ans*n;
}
cin >> oper;
}
cout << "answer: " << ans << endl << endl;
cout << "Press esc to exit or press any key to continue." << endl << endl;
c=getch();
if(c==27){
break;
}
}
return 0;
}
Here's my take at it, without making a class. Completely new from yours.
#include <iostream>
#include <cstdlib>
using namespace std;
double a, b;
char operation;
int main()
{
cout << "Welcome to my calculator program.\n";
cout << "To make a calculation simply use the following operators -> (+ - * /).\n";
cout << "To exit, simply write an operation but replace the operator with 'q'. (eg. 2q3).\n";
while (operation != 'q'){
cin >> a >> operation >> b;
if(std::cin.fail()){
cout << "Input not numerical. Exiting...";
exit(1);
}
switch (operation)
{
case '+':
cout << " = " << a + b << '\n';
break;
case '-':
cout << " = " << a - b << '\n';
break;
case '*':
cout << " = " << a * b << '\n';
break;
case ':':
case '/':
cout << " = " << a / b << '\n';
}
}
return 0;
}
Related
#include<iostream>
#include<cmath>
#include<string>
#include<fstream>
using namespace std;
struct Calculations //structure to hold the numbers and operators from 'equation'
{
double num1;
char operators;
double num2;
double answer;
};
Calculations myCalculationArray[SIZE]; // the array of calculations
int main()
{
while (i = 0; i <= 5; i++;)
{
cout << "Enter equation: \n";
getline(cin, equation);
cout << equation;
}
}
Alright so I'm trying to build a calculator where the user inputs an equation like "22/2", then to have it like assign the first number to num1 = ' 22 ' and the operator =' / ' to operators etc.
Since it seems like it is an homework for a student I will give you another solution for a calculator and you can modify it as you like ;)
#include<iostream>
#include<cmath>
using namespace std;
int main() {
char op;
float num1, num2;
cout << "Enter two operands: ";
cin >> num1 >> op >> num2;
switch(op)
{
case '+':
cout << num1+num2;
break;
case '-':
cout << num1-num2;
break;
case '*':
cout << num1*num2;
break;
case '/':
cout << num1/num2;
break;
default:
// If the operator is other than +, -, * or /, error message is shown
cout << "Error! operator is not correct";
break;
} }
You can take the help of strtok, strchr for parsing the string (separating out the operation symbol and the two numeric operands).
To convert the numeric string such as "34" to 34 , you can use the functions like atoi and atod etc.
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; }
In my class one of our assignments is to convert a prefix equation to infix. After reading that section I still have no idea what I'm doing. The book had some code that will solve a prefix equation when given but I have no idea how it does it or how I would display the infix version. Any help would be appreciated in explaining how this code finds the solution and how I could have it display a infix version.
#include <iostream>
#include <string>
#include <stdlib.h>
#include <sstream>
using namespace std;
int prefixExpr(istream &exprStream);
int main() {
string input;
cout << "Enter prefix expressions to evaluate. \nPress enter after each expression, and press enter on a blank line to quit." << endl;
cout << "Enter a prefix expression to evaluate: ";
getline(cin, input);
while (input.size() != 0){
istringstream exprStream(input);
cout << prefixExpr(exprStream) << endl;
cout << "Enter a prefix expression to evaluate: ";
getline(cin, input);
}
return 0;
}
int prefixExpr(istream &exprStream) {
char ch = exprStream.peek();
while (isspace(ch)) {
ch = exprStream.get();
ch = exprStream.peek();
}
cout << ch << endl;
if (isdigit(ch)) {
int number;
exprStream >> number;
cout << number << endl;
return number;
}
else {
ch = exprStream.get();
int value1 = prefixExpr(exprStream);
int value2 = prefixExpr(exprStream);
switch (ch) {
case '+': return value1 + value2;
case '-': return value1 - value2;
case '*': return value1 * value2;
case '/': return value1 / value2;
default: cout << "Bad input expression";
exit(1);
}
}
}
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 :(";