我需要制作一个 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 选项后,它什么也不做。
该算法首先找到间隔的长度。然后循环根据中点公式添加函数,这就是我认为我做错了什么的地方。