使用Riemann Sum的C++集成解决方案:丢失超过10个分区的有效性

0 c++ integral

为了编写最简单的解决方案,我可以使用黎曼和来近似积分,我遇到了一个奇怪的问题:如果用户请求的分区数超过10,则程序失败.有什么想法吗?这是代码:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

Mit*_*eat 6

使用大于10的分区大小不是您的实际问题.

当你应该使用float或时,你正在使用整数作为变量和函数返回值double.

例如:

int width = (right - left) / R; 
Run Code Online (Sandbox Code Playgroud)

如果(right - left) < R宽度为零!