I'm writing a code for integration to find the definite integral using the area of trapezoids. I wanted to know if this looks correct, it's giving me 21.5 for an answer.
Also am I calling the array correctly? I didn't specific the size in main. Also, say the array was pass by function, would I have to do the same as with variables, and create a new array name in the main? Like... if the array was double& s[]...
in main:
double x[]={};
cout<<(x[];
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// Example program
#include <iostream>
#include <string>
usingnamespace std;
double integrate(double s[], int n, double t);
int main(){
double s[]={5,4,2,1,4,5,3};
std::cout<<integrate(s,7,1);
}
double integrate(double s[], int n, double t){
double ans;
for(int i=0;(i+1)<n;i++){
ans+=(s[i]+s[i+1])*t/2;}
return ans;
}
This looks correct to me, but it would be better to call integrate in this case with integrate(s, sizeof(s)/sizeof(s[0], 1);
That way if you change the size of the array, it will still work.
Oh, and you need to initialize ans=0.0 at line 14. Othewise you're just adding to some random value.
Finally, change the indenting at line 17. The return statement should be at the same level as the for at line 15.