首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Stirling近似产生与预期不同的输出

Stirling近似产生与预期不同的输出
EN

Stack Overflow用户
提问于 2015-04-01 15:05:51
回答 1查看 41关注 0票数 0

所以我对C很陌生,并且慢慢地学习语法。不过,我遇到了一个问题。所以我试图证明Stirlings近似

ln (N!) =N ln (N) - (N)

因此,当我在代码中创建print语句来测试数组的每个元素是否正在产生数组的输出时,我希望它是一个数字。还远没有呢。

代码语言:javascript
复制
#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语句,它将产生以下输出

代码语言:javascript
复制
 Element[2] = 688
 Element[3] = 2048
 Element[4] = 1232
 Element[5] = 688
 .....
 .....
 Element[100] = 544

我确信这些都是数字,不应该在输出上吐出来,所以有人能解释为什么吗?谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-04-01 15:11:49

没有打印正确的数据类型。

代码语言:javascript
复制
printf ("Element[%d] = %d\n", i, x);

它想打印一个int类型。请尝试

代码语言:javascript
复制
printf ("Element[%d] = %e\n", i, x);

您还必须这样声明数组

代码语言:javascript
复制
static double natural_array[101];

或者减少循环限制。最好把这两个人绑在一起,也许是这样。

代码语言:javascript
复制
#define ELEMENTS 100
...
static double natural_array[ELEMENTS]; 
...
for (i = 2; i < ELEMENTS; i++) { 
    ...
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29394348

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档