do-while, math

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);

}
while (k<4);

cout<<"sum is "<<sum<<"";
return 0;
}
double f(double x)
{
double y;
y=2*x;
return y;
}
You are adding f(a + h) twice and also adding f(a + 4h).
Just unroll your loop and you will see.
Before loop: sum=f(a+h);
First iteration: k=1, t=1: sum=sum + f(a+1*h); //sum = f(a+h) + f(a+1*h)
Last iteration: k=4, t=4: sum=sum + f(a+4*h); //sum = f(a+h) + f(a+1*h) + ... + f(a+4*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<<"";

}
double f(double x)
{
double y;
y=2*x;
return y;
}
1/2 < integer division here (1/2 = 0). Use 1.0/2.0 (1.0/2.0 = 0.5)
h=(b-a)/n; Also here. Change to h = (b - a) / static_cast<double>(n);
MiiNiPaa.. Thank you very much! I look forward to try later. Thank you!
Topic archived. No new replies allowed.