area under curve help

Hi, I've been using C++ to calculate the approx area under a graph with trapezium rule.

The graph I want to calculate the area under is y=1/x with lower limit "a" and upper limit "b".

However when I put values in, the answer turns out to be far off.
Here is my c++ list. Someone please identify the problem:

#include <iostream>
using namespace std;
int main ()
{
int n,k; // n represents the number of strips
float a, b, p, Sn, I;
cout << "insert lower limit";
cin >> a;
cout << "insert upper limit";
cin >> b;
cout << "insert number of strips";
cin >> n;
p = (b-a)/n;
for(k=1; k<n; k++)
{
Sn =+ 2/(a + k*p);
}
Sn =+ ((1/a) + (1/b));
I = (p/2)*Sn;
cout << I << endl;
return 0;
}

Last edited on
What is this??
Sn =+ 2*(a + k*p);
I'm thinking in particular about the =+ part
How are you expecting that to work (I'm checking on
your knowledge of c++ operators).
Last edited on
so Sn = 2/[ (a + p) + (a +2p) + (a + 3p) +... (a+ (n-1)p) ]

(sorry I edited it its supposed to be / and not * I changed it now in the OP)
can anyone see any problems?
The code seems somewhat unintuitive to me, so I will just point out as guestgulkan did -

a += b; // means a = a + b

is not the same as

a =+ b; // means a = +b which is the same as a = b

This is the first thing that comes to mind.

Also, you don't initialize Sn with zero, so it may contain rubbish.
Last edited on
Thank you KRA :) I got the + and = in the incorrect order
Topic archived. No new replies allowed.