-2

中点法を使用して 3 次多項式の積分を計算する C プログラムを作成する必要があります。

基本的にこれを統合します: f(x) = mx^3 + nx^2 + px + q ブロック/中間点法を使用します。

これまでのところ、私はこれを持っています:

#include <stdio.h>
#include <math.h>
int main(){
    char option;
    float m, n, p, q, a, b, N, S=0,T,h;//S for midpoint, T for Trap, h for interval length
    do{
        printf("\n Select one of following options:\n");
        printf("a)Enter new coefficients (m,n,p, and q)\n");
        printf("b)Enter the value for the range from a to b, and N, the number of intervals\n");
        printf("c)Calculate the integral from a to b\n");
        printf("d)Exit\n");

        option=getc(stdin);
        printf("You have selected option: \"%c\" \n", option);

        switch (option){
        case 'a':
            printf("Enter m,n,p,q (in this order):\n");
            scanf("%f%f%f%f", &m,&n,&p,&q);
            break;
        case 'b':
            printf("Enter the interval from a to b and the number of intervals N:");
            scanf("%f%f%f", &a, &b, &N);
            break;
        case 'c':
            h = (b - a) / N;
            for (float i = a; i < b - h; i + h){
                S =+(m*pow(i, 3)) + n*pow(i, 2) + p*i + q;
            }
            S = S*h;
            printf("The integral using midpoint rule: %f", S);
            break;
        case 'd':
            printf("Exit.\n");
            break;
        default:
            printf("Invalid entry, try again... \n");
            break;
        }
    } while (option != 'd');
    return 0;
}

これは私が使用しようとしている主なアルゴリズムです:

h = (b - a) / N;
            for (float i = a; i < b - h; i + h){
                S =+(m*pow(i, 3)) + n*pow(i, 2) + p*i + q;
            }
            S = S*h;
            printf("The integral using midpoint rule: %f", S);
            break;

しかし、それは機能していません。ループ部分に引っ掛かります。他のすべての変数を入力して c オプションを選択すると、何も実行されないためです。

アルゴリズムは、間隔の長さを見つけることから始まります。次に、ループは中点式ごとに関数を追加します。ここで、何か間違ったことをしたと思います。

4

2 に答える 2

2

一般に、ループ カウンターに浮動小数点変数を使用することは、浮動小数点値を比較して等しいかどうかを判断するのが難しいため、不適切な方法と見なされます。回避int策として、 をカウンターとして使用し、それに浮動小数点デルタを掛けます。

double delta = (b - a) / N;
double start = a + delta / 2.0;

for (int i = 0; i < N; i++) {
    double x = start + delta * i;

    // do calculations with x
}
于 2014-09-27T03:03:23.973 に答える
0

ループを修正しました:

h = (b - a) / N /2;
            for (float i = a+h; i < b; i=i + 2*h){
                S = S+(m*pow(i, 3)) + n*pow(i, 2) + p*i + q;
            }
            S = S*h*2;

今は完璧に動作します。

于 2014-09-27T01:22:51.703 に答える