所以我是C的新手,慢慢学习语法。我遇到了一个问题。所以我试图证明Stirlings近似在哪里
ln(N!)= N ln(N) - (N)
因此,当我在代码中创建print语句来测试数组的每个元素是否产生数组的输出时,我想要它的数字。它离它很远。
#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;
}
使用粗体的print语句生成此输出
Element[2] = 688
Element[3] = 2048
Element[4] = 1232
Element[5] = 688
.....
.....
Element[100] = 544
我确信这些数字不应该在输出上吐出来,所以任何人都可以解释它为什么?谢谢!
答案 0 :(得分: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++) {
...