2016-10-23 3 views
0

나는 계수의 값을 물어 동적으로 할당 된 배열, 변수의 값과 다항식의 차수에 저장했지만 다항식의 값을 포함해야하는 변수 p의 값은 초기화 한 후 업데이트되었습니다. I의 값이 X = 3, N = 3 (N ... 0) = {3,3,3,3} 및 반환 값 I 시도는 계산계수에 대해 동적으로 할당 된 배열을 사용하여 다항식을 계산할 때, 내가 뭘 잘못하고 있니?

#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; 
} 

답변

0
호너위한 방법을 사용한 3이다
a->nelem == n; 

은 할당이 아닌 사용되지 않은 값과의 비교입니다. 사용 된 배열은 데이터 유형 8byte double으로 갖는 한


p= a->arr[2]; 

이어야

p= a->arr[n]; 

a = malloc(sizeof(struct dynamic_arr)+sizeof(int)*(n+1)); 

이 충분한 메모리 아니다 int을 4 바이트 없다.

+0

두 번째 것은 실제로 디버깅하는 동안 n으로 대체 한 값이었습니다. – MatSiv97

+0

어쨌든 덕분에, – MatSiv97

+0

int에서 double 형식의 계수 유형을 변경 한 후 sizeof (int)의 데이터 형식을 변경하는 것을 잊어 버렸습니다. (실수로 보낸 경우에도 이전 주석을 편집 할 수없는 이유는 모르겠습니다.) – MatSiv97