【发布时间】:2013-12-15 22:43:16
【问题描述】:
好吧,我正在尝试编写一个程序,该程序使用辛普森的 3/8 规则对积分进行数值计算。我在将值从 Integral *newintegral 传递到 simpson() 函数时遇到问题。我对自己对结构和指针的理解没有太大的信心,而且我整天都在查看讲义和在线查看信息,但我仍然不明白为什么它不起作用。
当我尝试构建我的程序时,它出现了许多错误,特别是:在第 46 行“积分之前的预期表达式”和第 55-63 行中的大多数“'->' 的参数类型无效(有'Integral')我不明白为什么会发生第一个,因为我所有的讲师都是这种类型的例子,当将结构传递给函数时,只有语法func(Struct_define_name individual_struct_name)。我认为这就是我在做记事(Integral 是结构类型的名称,而 i 是特定结构)但显然不是。
我认为这两个问题是相关的,因此我将所有代码都包含在上下文中,但是实际上有错误的行是 46 和 55-63,如上所述。不过,我可能一开始就定义了错误的结构。
(顺便说一句,simpson() 函数中的数学现在实际上并不能正常工作,但这不是我关心的问题)
我还尝试查看其他类似的问题,但我不明白其他代码在做什么,因此我无法推断如何修复我的代码。我知道这与其他人不太相关,但我真的不太了解编程,无法在一般意义上尝试表达我的问题......
'#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct integral {
double result, limits[2];
int degree;
double coefficients[];
} Integral;
// Prototype of function that calculates integral using Simpson's 3/8 rule
double simpson(Integral i);
// function (?) which initialises structure
Integral *newintegral() {
Integral *i = malloc(sizeof *i);
double lim1_in, lim2_in;
int degree_input, n;
printf("Please enter the degree of the polynomial.\n");
scanf("%d", °ree_input);
i->degree = degree_input;
printf("Please enter the %d coefficients of the polynomial, starting\n"
"from the highest power term in the polynomial.\n", (i->degree+1));
for (n=i->degree+1; n>0; n=n-1) {
scanf("%lg", &i->coefficients[n-1]);
}
printf("Please enter the upper limit of the integral.\n");
scanf("%lg", &lim1_in);
i->limits[0] = lim1_in;
printf("Please enter the lower limit of the integral.\n");
scanf("%lg", &lim2_in);
i->limits[1] = lim2_in;
return i;
}
int main() {
Integral *i = newintegral();
simpson(Integral i);
return 0;
}
double simpson(Integral i) {
int n;
double term1, term2, term3, term4;
for (n=(i->degree); n>0; n=n-1) {
term1=(pow(i->limits[1],n)*(i->coefficients[n]))+term1;
term2=(pow(((((2*(i->limits[1]))+(i->limits[0])))/3),n)*(i->coefficients[n]))+term2;
term3=(pow(((((2*(i->limits[0]))+(i->limits[1])))/3),n)*(i->coefficients[n]))+term3;
term4=(pow(i->limits[0],n)*(i->coefficients[n]))+term4;
}
i->result = (((i->limits[0])-(i->limits[1]))/8)*(term1+(3*term2)+(3*term3)+term4);
printf("The integral is %lg\n", i->result);
return 0;
}'
【问题讨论】: