首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我的差分函数不产生实际的差并返回零?

为什么我的差分函数不产生实际的差并返回零?
EN

Stack Overflow用户
提问于 2015-04-02 00:12:37
回答 1查看 41关注 0票数 0

所以我对C不熟悉,并试图证明Stirlings近似。natural_log和近似值函数确实根据我测试的结果工作。现在,我正在学习如何将这些数组解析为差分函数。我在线查看了代码,看起来我正确地使用了语法,但它并没有给出我想要的结果。

代码语言:javascript
复制
#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;
}

所以当我运行这个程序时,它会产生这个输出。

代码语言:javascript
复制
Element[0] = 0.0000
Element[1] = 0.0000
Element[2] = 0.0000
....
....
Element[100] = 0.0000

我知道,当我运行打印函数的检查行时,自然日志和近似是有区别的,但是它似乎没有得到这些数字,有什么想法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-04-02 00:46:33

代码使用错误的参数调用函数,从而导致未定义的行为。

例如,必须使用两个参数调用double * difference (double * natural_array, double * approximation_array)。但你写道:

代码语言:javascript
复制
difference();

main中。通常编译器会对此进行诊断并打印错误消息,但是您可以通过编写非原型声明double * difference ();来禁用该特性。

您应该做的第一件事是删除所有非原型声明。要么使用原型(例如double * difference (double *, double *);),要么将函数体按不同的顺序放置,这样就不需要进行前向声明。

不使用参数的函数应该具有参数列表(void),而不是()

在此之后,您需要重新设计函数参数和返回值,以便您需要的数组可用。例如,natural_log()approximation()函数工作在包含在这些函数中的数组上,并且永远不会在函数之外公开这些数组。相反,您需要让difference处理这些数组。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29403024

复制
相关文章

相似问题

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