[英]Horner's rule in C
因此,我正在編寫一個使用Horner規則計算多項式的程序。
但是在我輸入第一個系數后,程序崩潰了。 我做錯了什么? 我找不到錯誤。
編輯:我只是注意到我在向后讀參數。
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", °ree);
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;
}
當您分配內存a
, degree
尚未被初始化。
同樣,從scanf("%f", *(a+i));
刪除星號scanf("%f", *(a+i));
。 您需要a[i]
的地址 ,而不是其value 。
在您的代碼中, 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", °ree);
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.