Search code examples
c++functionadditionarithmetic-expressions

Addition in C++


I'm beginning to write a calculator program in C++ and I'm not able to get the addition to work right. I've tried different types of numbers, using strings and then casting to an int, encapsuling the function in a class, all with no avail. Help would be greatly appreciated, I'm new to C++ (Java is my main language). Thanks!

#include <iostream>
#include <math.h>
#include <string>
using namespace std;

int calcIt(int a, char b, int c){
    int result = 0;
        if(b == '+'){
            result =(a+b);
        }
    return result;
}
int main(){
    int aa;
    char bb;
    int cc;
    cout << "Int a: " << endl;
    cin >> aa;
    cout << "Operand: " << endl;
    cin >> bb;
    cout << "Int b: " << endl;
    cin >> cc;
    cout << "That is: " << calcIt(aa,bb,cc) << endl;
    return 0;
}

Solution

  • #include <iostream>
    #include <math.h>
    #include <string>
    using namespace std;
    
    int calcIt(int a, char b, int c){
        int result = 0;
        if (b == '+'){
            result = (a + c);  // <<------ this was a + b
        }
        return result;
    }
    int main(){
        int aa;
        char bb;
        int cc;
        cout << "Int a: " << endl;
        cin >> aa;
        cout << "Operand: " << endl;
        cin >> bb;
        cout << "Int b: " << endl;
        cin >> cc;
        cout << "That is: " << calcIt(aa, bb, cc) << endl;
        return 0;
    }