所以我是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
我敢肯定,这些都是它不应该在输出被吐出这样任何人都可以解释为什么这是一个数字?谢谢!
'natural_array [99];'必须有'101'元素可以通过'100'索引,作为一个问题。 – 2015-04-01 15:10:19
你的数组有99个元素,索引为0到98.你的循环上溯到索引100,它是元素101.索引超出界限导致[*未定义行为*](http://en.wikipedia.org/wiki/ Undefined_behavior)。 – 2015-04-01 15:10:24