为什么我在C语言中得到了关于Horner规则的错误输出
fx=a0+a1*x+a2*x2+…+an*xn 首先,我创建一个动态数组来存储。 然后我定义了一个函数来描述霍纳规则,但是不管我如何改变输出的方式,我只得到了一个巨大的数字。代码怎么了为什么我在C语言中得到了关于Horner规则的错误输出,c,C,fx=a0+a1*x+a2*x2+…+an*xn 首先,我创建一个动态数组来存储。 然后我定义了一个函数来描述霍纳规则,但是不管我如何改变输出的方式,我只得到了一个巨大的数字。代码怎么了 #include <stdio.h> #include <malloc.h> int f(int n, int *p, int x); int main() { int *pA; int length; int x; int i; print
#include <stdio.h>
#include <malloc.h>
int f(int n, int *p, int x);
int main() {
int *pA;
int length;
int x;
int i;
printf("input the length of Array:"); ///createArray of 'An'
scanf("%d", &length);
printf("please input x = ");
scanf("%d", &x);
pA = (int *)malloc(4 * length);
for (i = 0; i < length; i++) {
printf("input the No.%d element:", i + 1);
scanf("%d", &pA[i]);
}
printf("%d\n", f(length, pA, x)); ///Horner's rule
return 0;
}
int f(int n, int *p, int x) {
int i;
int pn = p[n - 1];
for (i = n; i >= 1; i--) {
pn = p[i - 2] + x * pn;
}
return pn;
}
给定多项式
f(x) = a0 + a1x + a2x2 + ... + anxn
这将解决OP代码中的问题,其中条件i>=1会导致循环体向下执行到i==1,从而导致数组p[i-2]=。。。变成p[-1]=
还要注意的是
#include <malloc.h>
// ...
int *pA;
// ...
pA = (int *)malloc(4 * length);
// ^^^^^^^ ^
// ...
可以写成
#include <stdlib.h>
// ...
int *pA = malloc((sizeof *pA) * length);
if ( !pA ) {
// Deal with the failed allocation, maybe exit(1)
}
// ...
free(pA); // <- Don't leak memory!
并给出一个简单的输入、预期和实际输出示例。还要检查您的数组索引是否没有超出范围。问题中提到的公式不是您在代码中计算的公式。最好提及您实现的版本。不要使用4*长度。使用sizeofint*length。这对我很有帮助,谢谢你,鲍勃!
double evaluate_poly_using_horner(size_t n, int const *c, double x)
{
if ( n == 0 )
return 0.0;
double result = c[n - 1];
for( size_t i = n - 1; (i--) > 0; )
{
result = c[i] + x * result;
}
return result;
}
#include <malloc.h>
// ...
int *pA;
// ...
pA = (int *)malloc(4 * length);
// ^^^^^^^ ^
// ...
#include <stdlib.h>
// ...
int *pA = malloc((sizeof *pA) * length);
if ( !pA ) {
// Deal with the failed allocation, maybe exit(1)
}
// ...
free(pA); // <- Don't leak memory!