繁体   English   中英

辛普森在C中的规则 - 答案不正确

[英]Simpson's rule in C - Incorrect answer

我编写了一个程序来计算函数曲线下的面积: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 );

}

谢谢你的帮助!

你声明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 -loop都会以ij从0到60(包括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));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM