好的,所以这个程序正在编译和运行除了它输出的区域为零的答案。 (注意,此函数是调用它的main的一部分)。我把最短的函数作为例子。
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define pi 3.1415927;
//Function to convert degrees to radians
float TrapezoidRule(float);
float SimpsonsRule(float);
float GaussQuadrature(float);
int main() {
int userInput, N;
float area, error;
printf("Choose which method to use to calculate the area of the function sin(x) from 0 to pi:\n");
printf("Enter 1 to use the Trapezoid Rule, enter 2 to use Simpson's Rule, enter 3 to use Gauss' Quadrature.\n");
scanf("%d", &userInput);
printf("\nEnter the number of intervals to use to calculate the area.\n");
scanf("%d", &N);
if (userInput == 1) { //Call Trapezoid rule function
printf("You are in this loop\n");
TrapezoidRule(area);
}
if (userInput == 2) {
SimpsonsRule(area);
}
if (userInput == 3) {
GaussQuadrature(area);
}
error = ((fabs(area - 2.0))/2.0)* 100;
//Print the area calculated using the chosen method
printf("\narea using chosen method = %.7f. Actual area = 2.0\n", area);
printf("The percentage error for your chosen method = %.7f\n", error);
return 0;
}
高斯求积函数如下所示:
#include <stdio.h>
#include <math.h>
double pi = 3.1415927;
int main (void) {
float area, a, b, h, k, error;
a = 0.0;
b = pi;
h = (b - a)/2;
k = a + h;
area = h * (sin(k + (h/sqrt(3.0))) + sin(k + (h/sqrt(3.0))));
//error = fabs(((area-2.0)/2.0) * 100);
printf("Area according to Gauss Quadrature = %.8f, True area = 2.0\n Error = %.8f percent\n", area, error);
return 0;
}
使用printf语句,我可以看到正确调用了该函数,但该函数中没有正确计算该区域。这可能与主要调用函数的方式有关吗?对不起,我非常喜欢初学者编程,对于如何正确调用和使用函数感到困惑。非常感谢您的帮助!
答案 0 :(得分:1)
由于函数float TrapezoidRule(float)
未定义,因此很难确定,但我猜这个函数会返回该区域。还读取了N变量,但从未使用过 - 它是函数的输入变量吗?
如果是这种情况,您需要将返回的结果存储在区域变量中:area = TrapezoidRule(N);
答案 1 :(得分:0)
//A function like
float TrapezoidRule(float);
应该有一个返回该区域的返回语句。
调用此功能时 使用像
这样的变量float newarea = TrapezoidRule( area) ;
现在'newarea'将存储从函数trapezoidrule
返回的值