2015-04-01 68 views
0

所以我是C的新手,並且慢慢學習語法。但我遇到了一個問題。所以我想證明斯特靈公式其中斯特林逼近產生不同於預期的輸出

LN(N!)= N LN(N) - (N)

所以,當我使代碼中的打印語句來測試是否該陣列的每個元素產生數組的輸出是我想要的數字。它遠非如此。

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

double * natural_log(); 
/* Obtain the natural log of 0 to 100 and then store each value in an array  */ 
double * 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(); */ 
    return 0; 
} 

double * natural_log() { 

    static double natural_array[101]; /* set up the array */ 
    int i; /* 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(2); 

    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] = %d\n", i, x);** 
    } 
    return natural_array; 
} 

double * approximation() { 

    static double approximation_array[99]; /* 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); 
    } 
    return approximation_array; 
} 

與打印語句以粗體它產生這樣的輸出

Element[2] = 688 
Element[3] = 2048 
Element[4] = 1232 
Element[5] = 688 
..... 
..... 
Element[100] = 544 

我敢肯定,這些都是它不應該在輸出被吐出這樣任何人都可以解釋爲什麼這是一個數字?謝謝!

+1

'natural_array [99];'必須有'101'元素可以通過'100'索引,作爲一個問題。 – 2015-04-01 15:10:19

+1

你的數組有99個元素,索引爲0到98.你的循環上溯到索引100,它是元素101.索引超出界限導致[*未定義行爲*](http://en.wikipedia.org/wiki/ Undefined_behavior)。 – 2015-04-01 15:10:24

回答

3

你是不是有

printf ("Element[%d] = %d\n", i, x); 

這要打印的int型打印正確的數據類型。請嘗試

printf ("Element[%d] = %e\n", i, x); 

還必須聲明數組從而

static double natural_array[101]; 

要麼,降低循環限制。將兩者結合起來可能是這樣的

#define ELEMENTS 100 
... 
static double natural_array[ELEMENTS]; 
... 
for (i = 2; i < ELEMENTS; i++) { 
    ... 
+0

它的工作原理,謝謝!我想這比我想象的更簡單 – 2015-04-01 15:15:26

+0

輕微:鑑於數字結果的種類繁多,建議在「%f」上方使用「%e」。 – chux 2015-04-01 15:59:40

+0

@chux現在編輯爲您的建議,謝謝。 – 2015-04-01 16:19:37