0
我詢問係數的值,將它們存儲在一個動態分配的數組中,變量的值和多項式的次數,但變量p的值應該包含多項式的值,在我初始化後更新。我試圖與值x = 3,n = 3的一個(N ... 0)= {3,3,3,3},並且返回值是3 我使用Horner的方法用於計算評估一個多項式,使用一個動態分配的數組作爲係數,我做錯了什麼?
#include <stdio.h>
#include <stdlib.h>
struct dynamic_arr
{
int nelem;
double arr[1];
};
double polynomial(struct dynamic_arr *a,int n, double x);
int main()
{
struct dynamic_arr *a;
int n;
double pl;
double x = 2;
int scancount;
do
{
printf("enter the degree of the polynomial: ");
scancount = scanf("%d", &n);
}
while (scancount == 0);
a = malloc(sizeof(struct dynamic_arr)+sizeof(int)*(n+1));
if (a == NULL)
{
exit(EXIT_FAILURE);
}
a->nelem == n;
do
{
printf("enter the coefficient of the %d degree monomial:", n);
scancount = scanf("%lf", &a->arr[n]);
while(getchar() != '\n')
;
}
while (scancount == 0 || n-- > 0);
do
{
printf("enter x :");
scancount = scanf("%lf", &x);
}
while (scancount != 1);
pl = polynomial(a,a->nelem,x);
printf("%f", pl);
free(a);
return 0;
}
double polynomial(struct dynamic_arr *a,int n, double x)
{
double p;
p= a->arr[2];
while (--n >= 0)
{
p = p*x+a->arr[n];
}
return p;
}
第二個實際上是在調試過程中我已經替換爲n的值。 – MatSiv97
無論如何,謝謝,我忘了 – MatSiv97
在將int係數的類型從int更改爲double之後,更改sizeof(int)中的數據類型(我不知道爲什麼即使我錯誤地發送了它,我也無法編輯以前的評論) – MatSiv97