所以我是C新手,试图证明斯特林斯逼近。 natural_log和approximation函数根据我测试的结果进行工作。现在我正在学习如何将这些数组解析为差异函数。我在网上查看了代码,看起来我正确地使用了语法,但它并没有给我想要的结果。为什么我的差异功能不会产生实际差异并回馈零?
#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;
}
所以,当我运行它,它产生这样的输出
Element[0] = 0.0000
Element[1] = 0.0000
Element[2] = 0.0000
....
....
Element[100] = 0.0000
我知道有在自然对数,当我跑了打印功能的检查线的近似差异,但它不” t似乎得到这些数字的任何想法?
看看调用差异()。你不传递任何参数... – 2015-04-02 00:17:48
这个循环:'for(i = 0; i <= 100; i ++){'调用未定义的行为,所以输出是正确的。当你调用未定义的行为时,任何事情都可能发生。 (它应该是:for(i = 0; i <100; i ++){'。)另外,请注意,顶部的函数声明都不是原型;如果你用原型声明了函数,那么你正在浪费编译器的能力,以帮助你避免问题。添加参数(当没有参数时为'void'),这样编译器就可以发现@MitchWheat指出的问题。 – 2015-04-02 00:17:52
你所有的三个函数都返回结果;你丢弃它们。 – 2015-04-02 00:25:53