辛普森在C中的统治 - 答案不正确

时间:2014-02-17 21:59:56

标签: c area

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

#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 );

}

感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

您声明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));