[英]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.