0

为了编写最简短的解决方案,我可以使用黎曼和来近似积分,我遇到了一个奇怪的问题:如果用户请求的分区计数超过 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;
}
4

3 回答 3

6

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

当您应该使用floator时,您正在使用整数作为变量和函数返回值double

例如:

int width = (right - left) / R; 

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

于 2010-01-25T05:10:25.520 回答
3

附带说明一下,除非您打算扩展这个小程序,否则您将包含许多无用的东西。这就是这个 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.
}

干杯:)

于 2010-01-25T05:22:31.603 回答
0

另一条评论:

在我看来,您代码中的 for 循环不会计算正确的黎曼和。我认为它应该是这样的:

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

干杯:)

于 2013-01-05T17:17:56.827 回答