tags:

views:

286

answers:

2

In an effort to code the briefest solution I could for an approximation of the integral using Riemann sums, I ran into a strange problem: if the user requested a partition count in excess of 10, the program failed. Any thoughts? Here's the code:

// The Integral

#include <algorithm>
#include <iomanip>
#include <ios>
#include <iostream>
#include <stdexcept>
#include <iomanip>

using std::cin;     using std::cout;
using std::endl;    

int func (int x);

int main () 
{   
    cout << "Please enter left and right bounds: ";

    int left, right;
    cin >> left >> right;

    cout << "Please enter a # of partitions (>0): ";

    int R;
    cin >> R;

    int width = (right - left) / R;
    int total = 0;

    for (int i = 0; i < R; ++i) {
        total += func(left + width*i);
    }   

    cout << "The integral is: " << total << endl;

    return 0;
}

int func (int x) 
{
    return x*x;
}
+5  A: 

Using a partition size of greater than 10 is not your actual problem.

Your are using integers for your variables and function return value, when you should be using float or double.

For instance:

int width = (right - left) / R; 

If (right - left) < R width will be zero!

Mitch Wheat
+1  A: 

on a side note, unless you plan on expanding this small prog, you're including way to many useless stuff. this is all you'd need for this prog:

#include <iostream>
#include <cstdio>
using namespace std;

int func (int x) 
{
    return x*x;
}

int main()
{
// if you have your main() at the bottom, you dont have to declare other functions on top.
}

cheers :)

aZn137