Invalid operands to binary expression (double (int))

Sep 11, 2015 at 9:14am
Writing a code that approximates π using Leibniz’ formula. I get errors at the += and -= sign (invalid operands to binary expression double(int and double). Help?

[code]

#include <iostream>

using namespace std;


double pi (int n) {

double denom = 1;

bool condition = true;

for (int i = 1; i <= n; i++){

if (condition)
{
pi += (4 / denom);
}
else
{
pi -= (4 / denom);
}
condition = !condition;
denom += 2;


}

}


int main(){

int n;
cin >> n;
pi(n);
cout << "Result:" << endl;
cout << pi << endl;
return 0;

}
Last edited on Sep 11, 2015 at 9:15am
Sep 11, 2015 at 9:37am
pi is a function. You cannot add or subtract something from it, you can only call it. You probably want to create some variable and place result there.

Also you never return anything from it, so whole function is meaningless right now.

pi(n); Call function, discard result. Meaningless.

cout << pi << endl;Output function address. To output function call result, you should actually call it.

Example of using functions properly:
1
2
3
4
5
6
7
8
9
10
11
12
double add(double l, double r)
{
    //Calculations
    double result = l + r;

    //Return result to caller
    return result;
}

//...
//Output result of function call
std::cout << add(5.1, -2.1) << '\n';
Sep 11, 2015 at 11:41am
closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
using namespace std;

double pi (int n)
{
    double PIN = 0;
    double denom = 1;
    bool condition = true;
    
    for (int i = 1; i <= n; i++)
    {
        if (condition)
        {
            PIN += (4 / denom);
        }
        else
        {
            PIN -= (4 / denom);
        }
        
        condition = !condition;
        denom += 2;
    }
    return PIN;
}

int main(){
    int n;
    double piEstimate = 0;

    cout << "Number of terms: ";
    cin >> n;
    
    piEstimate = pi(n);
    cout << "Result: " << piEstimate << endl;
    
    return 0;
}
Topic archived. No new replies allowed.