2014-01-05 24 views
1

所以我正在編寫一個程序,使用Horner的規則來計算多項式。Horner的規則C

但是當我輸入第一個係數後程序崩潰了。我做錯了什麼?我找不到錯誤。

編輯:我只是注意到,我正在讀的參數向後。

int main() { 

    int degree; 
    float x; 
    float px = 0; 
    float p = 0; 
    float *a; 
    int i; 

    a = malloc((degree+1)*sizeof(float)); 

    printf("Enter the degree:"); 
    scanf("%d", &degree); 
    printf("Enter the argument:"); 
    scanf("%f", &x); 

    for (i = 0; i < degree+1; i++) 
    { 
    printf("Enter the coefficient Nr%d:", i+1); 
    scanf("%f", *(a+i)); 
    } 
    for (i = degree; i > -1; i--) 
    { 
    p = *(a+i) * pow(x, i); 
    px + p; 
    } 

    printf("%f", px); 

    return 0; 
} 
+0

'px + p;'assign to where? – Maroun

+0

我假設你在輸入'degree'後打算分配'a'? – Xymostech

+0

'p = *(a + i)* pow(x,i);'不是霍納的方法,你的意思是'px + = ...' –

回答

3

當您爲a分配內存,degree尚未被初始化。

此外,從scanf("%f", *(a+i));刪除星號。你需要地址a[i],而不是的值

+0

謝謝你現在的作品。 – user3004619

1

在您的代碼中,a = malloc((degree+1)*sizeof(float));您正在使用degree的值,但未對其進行初始化。一個初始化的變量可以包含ANY的值,最有可能是無效的,並且會帶您進入名爲的未定義行爲。這就是碰撞發生的原因。

第二件事,每次在malloc() [或者一般來說,一個庫函數或系統調用]之後,檢查返回值的有效性是一個非常好的主意。在這裏,您可以在malloc()之後使用a變量檢查NULL

三,將scanf("%f", *(a+i));更改爲scanf("%f", &a[i]);

也許如果你用以下方式編寫代碼,它應該可以工作。

int main() { 

    int degree; 
    float x; 
    float px = 0; 
    float p = 0; 
    float *a; 
    int i; 

    printf("Enter the degree:"); 
    scanf("%d", &degree); 
    printf("Enter the argument:"); 
    scanf("%f", &x); 

    a = malloc((degree+1)*sizeof(float)); 

    for (i = 0; i < degree+1; i++) 
    { 
    printf("Enter the coefficient Nr%d:", i+1); 
    scanf("%f", &a[i]); 
    } 
    for (i = degree; i > -1; i--) 
    { 
    p = *(a+i) * pow(x, i); 
    px + p; 
    } 

    printf("%f", px); 

    return 0; 
}