所以我是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似乎得到這些數字的任何想法?
看看調用差異()。你不傳遞任何參數... – 2015-04-02 00:17:48
這個循環:'for(i = 0; i <= 100; i ++){'調用未定義的行爲,所以輸出是正確的。當你調用未定義的行爲時,任何事情都可能發生。 (它應該是:for(i = 0; i <100; i ++){'。)另外,請注意,頂部的函數聲明都不是原型;如果你用原型聲明瞭函數,那麼你正在浪費編譯器的能力,以幫助你避免問題。添加參數(當沒有參數時爲'void'),這樣編譯器就可以發現@MitchWheat指出的問題。 – 2015-04-02 00:17:52
你所有的三個函數都返回結果;你丟棄它們。 – 2015-04-02 00:25:53