Simpsons Rule problem, need advice on fixing a few errors:

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/* 1. Write a program that uses either the trapezoidal rule or Simpson's Rule to estimate the value of the integral of the function 
f(x) = (1 + x^2)^2 over the interval (0,1). Run the algoritm to the 8th order (k = 8). The program should report the value of the estimate. */

#include <iostream>
#include <iomanip>
#include <string>
#include <math.h>
using namespace std;

void compute (int);
int findN (int);
double find_deltaX (int, int , int);
double find_S (int, int, double);

int main()
{
	int k = 8;
	
	compute(8);

	return 0;
}


void compute (int k)
{
	int i;
	int n;
	double delta_x;
	double s;
	int a = 0;
	int b = 1;
	
	cout << "  Order  " << "Number of Panels  " << "S Value     " << endl;
	
	for (i = 0; i <= k; i++)
	{
		n = findN(i);
		delta_x = find_deltaX (a, b, n);
		s = find_S(i, n, delta_x);
		
		
		cout << "  " << i << "  " << n << "  "  << s << "     "  << endl;
	}
		
}

int findN (int k)
{
	int n;
	n = int(( pow(2,k) ));
	return n;
}

double find_deltaX (int a, int b, int n)
{
	double delta_x;
	
	delta_x = (( b - a) / (pow(n,2)));
	return delta_x;
}

double find_S (int k, int n, double x)
{
	double s;
	double delta_xx;
	
	delta_xx = x;
	
	s = ((1/3)*(delta_xx)*((1) + (4 *(1 + delta_xx)) + 4));
	
	return s;
}


I got it to run, but Im having a problem because its saying the value for S is always 0 and it should change.
Last edited on
1/3 is performed using integer division and is always 0.
Thank you so much. I cant believe I didn't notice that haha. I was looking at that like for like 2 hours today and couldnt figure it out.

Now my output is:

1
2
3
4
5
6
7
8
9
10
Order  Number of Panels  S Value
0  1  4.33333
1  2  0.833333
2  4  0.192708
3  8  0.0472005
4  16  0.0117391
5  32  0.00293096
6  64  0.000732501
7  128  0.00018311
8  256  4.57767e-005


which is good, but does anyone know where I can look to find a good way to make that more orgranized sort of like a table? I know <iomanip> is what I need, but Im not sure on the whole format thing how I would go about it.

Thanks =)
Last edited on
Look at setw() to set the field width.
Topic archived. No new replies allowed.