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を超えるパーティションサイズを使用することは、実際の問題ではありません。

floatまたはを使用する必要がある場合は、変数と関数の戻り値に整数を使用していますdouble

例えば:

int width = (right - left) / R; 

(right - left) < R幅がゼロになる場合!

于 2010-01-25T05:10:25.520 に答える
3

ちなみに、この小さなプログラムを拡張する予定がない限り、多くの役に立たないものへの道を含めています。このプログラムに必要なのはこれだけです。

#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 に答える