Hey everyone. I want to program a c++ program which can calculate sum: sum=f(a+h)+f(a+2h)+f(a+3h), where f(x)=2*x, a=1, b=2, h=(b-a)/4 and in this case h=1/4. But the program i have written doesn’t work as it is supposed to because result should be 6,88 when i type in a=1 and b=2.
What is wrong with my program? plz help
# include <iostream>
# include <math.h>
# include <stdlib.h>
using namespace std;
double f(double x);
int main ()
{
int t,k;
double sum,h,a,b;
cin>>a;
cin>>b;
k=0;
t=0;
h=(b-a)/4;
sum=f(a+h);
do
{
t=t+1;
k=k+1;
sum=sum+f(a+t*h);
Tanks a lot for your help. Now i have written a similar program for calculating sum sum=f(a+(1/2)h)+f(a+3(1/2)h)+f(a+5(1/2)h)+f(a+7(1/2)h), where f(x)=2*x, a=0, b=1, h=(b-a)/4 and in this case h=1/4. But when i type in a= and b=1 the result is 0 which is wrong. I have tried with several examples but there always wrong.
What is wrong with my program? Please help
# include <iostream>
# include <math.h>
#include <iomanip>
# include <stdlib.h>
using namespace std;
double f(double x);
int main ()
{
int n,g,r,a,b;
double sum,h;
cin>>a;
cin>>b;
cin>>n;
h=(b-a)/n;
r=-1;
g=0;
sum=0;
do
{
r=r+2;
g=g+1;
sum=sum+f(a+r*(1/2)*h);
}
while (g<=n);
cout<<"Sum is "<<sum<<"";