所以我是C新手,慢慢学习语法。我遇到了一个问题。所以我试图证明 Stirlings 近似值,其中
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
我确定这些数字不应该在输出中吐出,所以任何人都可以解释为什么会这样吗?谢谢!
最佳答案
您没有打印正确的数据类型
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++) {
...
关于c - 斯特林近似产生与预期不同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29394348/