2015-04-02 51 views
0

所以我是C新手,试图证明斯特林斯逼近。 natural_log和approximation函数根据我测试的结果进行工作。现在我正在学习如何将这些数组解析为差异函数。我在网上查看了代码,看起来我正确地使用了语法,但它并没有给我想要的结果。为什么我的差异功能不会产生实际差异并回馈零?

#include <stdio.h> 
#include <stdlib.h> 
#include <math.h> 
#define ELEMENTS 100 

void natural_log(); 
/* Obtain the natural log of 0 to 100 and then store each value in an array */ 
void approximation(); 
/* Use the sterling approximation caluculate the numbers from 0 - 100 and then store it in an array */ 
double * difference(); 
/* Calculate the difference between the arrays */ 
double * percentage(); 
/* Calculate the percentage of the difference and return the array */ 

int main() { 
    natural_log(); 
    approximation(); 
    difference(); 
    return 0; 
} 

void natural_log() { 

    static double natural_array[ELEMENTS]; /* set up the array */ 
    int i, j; /* set up the integer to increase the array by a value */ 


    natural_array[0] = 0.0; /* set up the first value in the array */ 
    natural_array[1] = log(1.0); 

    double x; 
    x = natural_array [1]; 
    for (i = 2; i <=100; i++) { /* set up the for loop to increment the i */ 
     natural_array[i] = x + log(1 + i); 
     x = natural_array[i]; 
    /* printf ("Element[%d] = %f\n", i, x); Check */ 
    } 
} 

void approximation() { 

    static double approximation_array[ELEMENTS]; /* set up the array */ 
    int i; /* set up the integer to increase the array by a value */ 

    for (i = 0; i <=100; i++) { 
     approximation_array[i] = (i) * log(i) - (i); 
     /* printf ("Elements[%d] = %f\n", i, approximation_array[i]); Check */ 
    } 
} 
double * difference (double * natural_array, double * approximation_array) { 

    static double difference_array[ELEMENTS]; 
    int i; 
    for (i = 0; i < 100; i++) { 
     difference_array[i] = (natural_array[i] - approximation_array[i]); 
     printf ("Elements[%d] = %f\n", i, difference_array[i]); 
    } 
    return difference_array; 
} 

所以,当我运行它,它产生这样的输出

Element[0] = 0.0000 
Element[1] = 0.0000 
Element[2] = 0.0000 
.... 
.... 
Element[100] = 0.0000 

我知道有在自然对数,当我跑了打印功能的检查线的近似差异,但它不” t似乎得到这些数字的任何想法?

+0

看看调用差异()。你不传递任何参数... – 2015-04-02 00:17:48

+1

这个循环:'for(i = 0; i <= 100; i ++){'调用未定义的行为,所以输出是正确的。当你调用未定义的行为时,任何事情都可能发生。 (它应该是:for(i = 0; i <100; i ++){'。)另外,请注意,顶部的函数声明都不是原型;如果你用原型声明了函数,那么你正在浪费编译器的能力,以帮助你避免问题。添加参数(当没有参数时为'void'),这样编译器就可以发现@MitchWheat指出的问题。 – 2015-04-02 00:17:52

+0

你所有的三个函数都返回结果;你丢弃它们。 – 2015-04-02 00:25:53

回答

0

您的代码通过调用具有错误数量参数的函数导致未定义的行为。例如,double * difference (double * natural_array, double * approximation_array)必须用两个参数调用。但你写:

difference(); 

in main。通常,编译器会诊断并输出错误消息,但是通过编写非原型声明double * difference();来禁用该功能。

你应该做的第一件事是删除所有的非原型声明。可以使用原型(例如double * difference (double *, double *);),也可以按不同顺序放置函数体,以便不需要进行前向声明。

不带参数的函数应该有参数列表(void)而不是()

之后,您将需要重新设计您的函数参数和返回值,以便您需要的数组可用。例如,natural_log()approximation()函数对包含在这些函数中的数组起作用,并且您从不在函数外面公开这些数组。相反,您需要让difference在这些阵列上工作。