2015-04-02 37 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在這些陣列上工作。