gpt4 book ai didi

c - C 中的辛普森法则 - 错误答案

转载 作者:太空宇宙 更新时间:2023-11-04 02:04:57 31 4
gpt4 key购买 nike

我编写了一个程序来计算函数的曲线下面积:f = tan(x)。我做了一些修复(即 dim 必须大于 61)所以程序编译并运行但输出错误的答案!我认为错误出在汇总 Tan[j] 的 for 循环中,但不确定在哪里...

#include <stdio.h>
#include <math.h>

//Question 3a. Create a program that calculates the area under the curve of:
// y = tan(x) from 0 --> pi/3


//TODO: Declare function to change degrees to radians as in Ex. 3 of practical

float degtorad(float arg);
float pi = 3.1415927;

int main(void) {

int i, j, sum1 = 0, sum2 = 0;
int dim; //Loop index, Counter, Array dimension
float a, b, rad, h, Tan[dim], area ; //Return value of the function, Result array, Area, Coefficient
b = (float)(pi)/(float)(3);
h = ((float)(b - a))/((float)(dim - 1));

printf("\nPlease input a value for the step size.\n");
scanf("%d", &dim);
//TODO: Get table of tan as in Ex. 3
j=0;
for (i=0; i<=60; i++) {
rad = degtorad(i);
Tan[j] = tan(rad);
j=j+1;
}

/*
TODO: Calculate the are using Simpson's rule. Simpson's rule is the combination of the
trapezoid rule and the midpoint rule so different steps apply depending on if the step is
even or odd. */


//Check if dimension is odd
if (dim%2 == 1) {
for (i = 0; i < dim - 1; i++) {
//Rule for even number. This is where the trapezoid rule is applied.
if (i%2 == 0) {
sum1 = sum1 + Tan[i];
}
//Else is for the odd iterations that come from the midpoint rule.
else {
sum2 = sum2 + Tan[i];
}
}
//Calculating the area using Simpson's rule.

area = (h/3) * ((tan(a)) + (4 * sum2) + (2 * sum1) + (tan(b)));
printf("\nThe area under the curve is: %1.8f\n", area);
}

return 0;

}

//TODO: Definition of the function as in Ex. 3

float degtorad(float arg) {
return( (pi * arg)/180.0 );

}

感谢您的帮助!

最佳答案

您声明 Tan 的大小为 dim,但您在使用它之前没有对其进行初始化:

int dim; // dim isn't initialized
float Tan[dim]; // array Tan of size ?

因此,dim 是未定义的,Tan 的大小也是未定义的。

当你从用户那里得到 dim 时,你首先需要调用

scanf("%d", &dim);

然后用它声明Tan:

scanf("%d", &dim);
float Tan[dim];

ADDIT:但是,您的 for 循环在获取用户输入后使用 ij 运行0 到 60(含),与用户的输入无关。你想将它从 0 循环到 dim(不包括):

for(i = 0; i < dim; i++){

而且,由于 ij 每次迭代都具有相同的值,因此您不需要 j:

    rad = degtorad(i);
Tan[i] = tan(rad);
}

如果编译器没有启用所有警告(通常使用 -Wall 选项),您的编译器应该已经警告过您。如果是:永远不要忽略编译器警告!


此外,在实际编译您的程序时,我收到以下警告:

In function 'main':
19:7: warning: 'a' is used uninitialized in this function [-Wuninitialized]
h = ((float)(b - a))/((float)(dim - 1));

关于c - C 中的辛普森法则 - 错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21840110/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com